Skip to content

Instantly share code, notes, and snippets.

@louisstow
Created October 26, 2012 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save louisstow/3960910 to your computer and use it in GitHub Desktop.
Save louisstow/3960910 to your computer and use it in GitHub Desktop.
Synchronous require for the browser
/**
* Shim the require function used in node.js
*/
(function() {
if (window.require !== undefined)
throw 'RequireException: \'require\' already defined in global scope';
window.require = function(module) {
var url = window.require.resolve(module);
var request = new XMLHttpRequest();
request.open('GET', url, false);
request.send();
try {
eval(
"(function() {" +
request.response +
"})();"
);
} catch(e) {
console.error("Error loading "+module);
console.error(e);
}
return exports;
}
window.require.resolve = function(module) {
var r = module.match(/^(\.{0,2}\/)?([^\.]*)(\..*)?$/);
return (r[1]?r[1]:'./')+r[2]+(r[3]?r[3]:(r[2].match(/\/$/)?'index.js':'.js'));
}
// INFO initializing module cache
window.require.cache = new Object();
})();
@SabbaKilam
Copy link

Since some browsers reject synchronous XMLHttpRequests because they are deprecated, is there another shim using promises or generators (ES6/ES2015) that can used instead? I can't seem to find an example of that anywhere.
Thanks.

@reverland
Copy link

I encounter with the same problem..maybe put everything in a service worker if available

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