Multiple JS files in Chrome Extension - how to load them?

前端 未结 5 1125
遥遥无期
遥遥无期 2021-02-01 16:15

I\'ve wrote a Chrome Extension. My background.js file is quite large, so I want to split it to smaller parts and load specified methods when required (some kind of lazy-loading)

5条回答
  •  春和景丽
    2021-02-01 16:51

    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);
    }
    

提交回复
热议问题