简体   繁体   中英

Load local versions of the JS libraries hosted on a CDN

I would like to make an addon that loads my local JS libraries rather than the ones hosted on CDN. For example loading my own version of the scripts hosted here https://developers.google.com/speed/libraries/devguide?csw=1#Libraries .

One way I have thought is to listen to all requests, like in the following example but I don't know how do I tell the browser to load the local versions of the libraries.

appAPI.onRequest(function(resourceUrl, tabUrl) {

  if (resourceUrl.match(/.*/)) {
  //Load the local version of the libraries used by the website

  }
});

I have also found something similar to what I want to do in the demo version but I don't know if this is a viable option.

appAPI.resources.addInlineJS('Resources/jquery-2.1.1.min.js');

You have the right idea of how to achieve your goal. In principle, you can use the appAPI.webRequest.onRequest method to block page resources and inject your own version in its place. There is a potential side effect such as the page loading scripts out of sequence which can affect its overall functionality.

The following code is provided as-is and is not tested. Also note that on Internet Explorer the solution may not work if the local libraries are longer that due to its maximum string length.

background.js :

// Monitor page resource requests
appAPI.webRequest.onRequest.addListener(function(details, opaque) {\
    // Check if the request is for loadable local resource
    for (var i = 0; i < opaque.resource.length; i++) {
        if (details.requestUrl.indexOf(opaque.resource[i].src) !== -1) {
            // Load local resource
            appAPI.resources.addInlineJS(opaque.resource[i].local);
            // Block original request
            return {
                cancel: true
            };
        }
    }
}, {
    resource: [ // List of loadable local resources
        {
            src: '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
            local: 'local/jquery-2.1.1.min.js'
        }
    ]
});

[ Disclosure : I am a Crossrider employee]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM