Created
October 26, 2012 19:27
-
-
Save louisstow/3960910 to your computer and use it in GitHub Desktop.
Synchronous require for the browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(); | |
})(); |
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
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.