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

前端 未结 5 1122
遥遥无期
遥遥无期 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

    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
      },
      ...
    }
    

提交回复
热议问题