Skip to content

Instantly share code, notes, and snippets.

@bga
Created August 26, 2010 22:26
Show Gist options
  • Save bga/552380 to your computer and use it in GitHub Desktop.
Save bga/552380 to your computer and use it in GitHub Desktop.
(function($G)
{
var cache = {};
var XHR = $G.XMLHttpRequest || function(){ return new $G.ActiveXObject('Microsoft.XMLHTTP') };
$G.require = function(url)
{
if(!(url in cache))
{
var xhr = new XHR();
xhr.open('GET', url, false);
xhr.send();
if(200 <= xhr.status && xhr.status < 300)
cache[url] = (new Function('var export = {};' + xhr.responseText + '; return export;')).call($G); // may be ES5 strict mode
else
cache[url] = null;
}
if(cache[url] == null)
throw url + ' not found';
else
return cache[url];
};
})(this);
/*
Why its bad.
1) non cross domain
2) block js while file is loading
3) debugging eval (or new Function) is hell. You dont know nor script file name nor line number. And modern js engines hasnt support of something like eval(code, fileName, lineNumber)
Result
Use normal asynch module load via script tag. CommonJS is not for client-side
*/
@GarrettS
Copy link

Oh I see the "Why its bad." code comment. Yes, blocking using sync requests is very bad. That was a big mistake of Dojo and they kept with it, incredulously, for many years. And so in light of that, it is surprisingly disturbing to see that strategy reemerge. Incredulous, and there it is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment