Multiple JS files in Chrome Extension - how to load them?
UPDATE : This solution works only if you are using manifest V2.
You can also do this the extremely easy way that is described here: https://developer.chrome.com/extensions/background_pages#manifest
{
"name": "My extension",
...
"background": {
"scripts": [
"lib/fileone.js",
"lib/filetwo.js",
"background.js"
]
},
...
}
You won't be doing lazy loading, but it does allow you to break your code up into multiple files and specify the order in which they are loaded onto the background page.
You could attempt to use web workers, perhaps. In your background.js, include:
var worker = new Worker('new-script.js');
Web workers can spawn new workers, and even have an importScript("new-script.js") method.
Web workers can tend to be very limited, however. Check here for a great article on Web workers.
I don't know if they would work, however. The other option is using XMLHTTPRequest (AJAX) to dynamically retrieve the script, and eval it. Over a non-HTTPS connection however, this is probably blocked due to man-in-the-middle attacks.
Alternatively, you can force Chrome to eval script from a non-encrypted connection (BUT DON'T DO IT) by adding this to manifest.json
:
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"permissions": ["http://badpractic.es/insecure.js"]
See Load remote webpage in background page: Chrome Extension for a more in-depth discussion of the AJAX method.
So your options seem to be limited.
This of course loads them all at once:
{
"name": "My extension",
...
"background": {
"scripts": ["background.js","background2.js","background3.js"] //and so on
},
...
}
If you want to load a javascript file in the context of your background page and want to avoid using eval
, you can just add a script
tag to your background page's DOM. For instance, this works if your files are present in the lib
folder of your extension:
function loadScript(scriptName, callback) {
var scriptEl = document.createElement('script');
scriptEl.src = chrome.extension.getURL('lib/' + scriptName + '.js');
scriptEl.addEventListener('load', callback, false);
document.head.appendChild(scriptEl);
}