簡體   English   中英

加載CDN上托管的JS庫的本地版本

[英]Load local versions of the JS libraries hosted on a CDN

我想制作一個加載程序,加載我的本地JS庫,而不是CDN上托管的庫。 例如,加載我自己的托管在https://developers.google.com/speed/libraries/devguide?csw=1#Libraries的腳本的版本。

我想過的一種方法是監聽所有請求,例如下面的示例,但是我不知道如何告訴瀏覽器加載庫的本地版本。

appAPI.onRequest(function(resourceUrl, tabUrl) {

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

  }
});

我還發現了與演示版本中類似的操作,但我不知道這是否可行。

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

您對如何實現目標有正確的想法。 原則上,您可以使用appAPI.webRequest.onRequest方法來阻止頁面資源並在其位置插入您自己的版本。 有潛在的副作用,例如頁面加載腳本不正確可能會影響其整體功能。

以下代碼按原樣提供,未經測試。 另請注意,如果本地庫由於其最大字符串長度而更長,則在Internet Explorer上該解決方案可能無法工作。

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

[ 披露 :我是Crossrider員工]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM