I am creating a google chrome extension which, when activated on a tab, loads some custom code and a few new views into the document of that window. I\'d like to use requireJS
Content scripts run in a context that is isolated from the page's context. I.e. if the page declares a global variable Backbone
, your content script cannot directly read or access it.
Drop the following code (just written) in your Chrome extension (put it after require.js
), and you will be able to use RequireJS in your content scripts.
require.load = function(context, moduleName, url) {
url = chrome.extension.getURL(url);
var x = new XMLHttpRequest();
// Append Math.random()... to bust the cache
x.open('GET', url + '?' + Math.random().toString(36).slice(-4));
x.onload = function() {
var code = x.responseText;
x += '\n//@ sourceURL=' + url; // Optional, for debugging.
window.eval(code);
context.completeLoad(moduleName);
};
x.onerror = function() {
// Log error if you wish. This is usually not needed, because
// Chrome's developer tools does already log "404 Not found"
// errors for scripts to the console.
};
x.send();
};
During development, this method is quite ideal, because the line numbers will match the lines in your code.
In production, I suggest to use r.js to concatenate (and minify) your code, because the output will be one big JavaScript file. Resources within a Chrome extension are typically loaded within a few milliseconds, but if you have quite a lot of modules, these milliseconds will add up to something significant. And each request is visible in the Network tab in the developer tools for the given tab, which is just noise, and an undesired side-effect for web developers who use your extension.