![](/img/trans.png)
[英]Internet Explorer Tracking Protection Prevents JQuery and Other Libraries from Loading
[英]Loading a second version of jQuery, and other libraries along with it
我正在制作一個由一段代碼組成的小部件,該代碼段可放入您的網站,然后通過js提取內容。 這是一個示例片段:
<div data-token="bc1cea6304e8" id="my-widget">
<script src="http://localhost:8080/assets/eg-widget.js" type="text/javascript"></script>
</div>
我正在做一個測試,以檢查頁面是否已經有jQuery,如果是,則該版本至少為1.5。
if (typeof jQuery == 'undefined' || isVersion("1.5", ">")) {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js");
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else { // Other browsers
script_tag.onload = scriptLoadHandler;
}
} else {
// The jQuery version on the window is the one we want to use
jQueryEg = window.jQuery;
scriptLoadHandler();
}
無論哪種情況,我們都將變量jQueryEg設置為我們決定使用的jQuery,以便避免沖突。
如果尚未加載jQuery,則一切正常。 但是,如果加載了舊版本,則在嘗試加載其他庫(如jQuery-ui)時會發生沖突。
為此,我們將window.jQuery設置為新加載的jQuery,以便在加載jquery-ui和bootstrap.js時,它們對window.jQuery或$的引用指向正確的版本。
問題在於,有時在我們將window.jQuery設置為我們的版本的同時,頁面的其他部分正在調用jQuery,這會導致問題。
關於如何避免這些沖突的任何想法?
jQueryEg = window.jQuery.noConflict(true);
window.jQueryEg = jQueryEg;
// jquery-ui reference window.jQuery so we need to set that to our new jquery for a sec
if (jQueryEg.ui == undefined || jQueryEg.ui.datepicker == undefined) {
var otherjQuery = window.jQuery;
window.jQuery = jQueryEg;
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
script_tag.onload = function () {
window.jQuery = otherjQuery;
main();
};
}
有一次我遇到類似的問題 。 在查看jQuery-UI代碼時,我注意到它們全部包裝在立即調用的函數表達式中(或者我自己包裝了它?我不記得了):
( function ( jQuery, undefined ){
// Code here...
})( jQuery );
創建私人范圍 。 所以我的解決辦法是
jQuery
保存到jQuery_OLD
jQuery
所以下面給出了這個想法
<script src="jquery-1.4.js"></script>
<script>
var jQuery_1_4 = jQuery.noConflict();
</script>
<script src="jquery-1.8.js"> </script>
<!-- load jquery UI -->
<script src="jquery-ui.js"> </script>
<!-- restore window.jQuery -->
<script>
jQuery = jQuery_1_4;
</script>
之前遇到過這種確切的情況,最終確定是您可能已經知道的,並且不想聽到:加載這樣的外部庫的多個版本時,根本沒有避免所有邊緣情況的好方法,由於您已經指定的原因。 所涉及並發症的摘要是:
不幸的是,唯一的答案是顯而易見的:在自己的服務器上托管庫的修改版本。
當然,您不需要一直提供這些版本,因此您仍然可以受益於Google CDN的使用。 同時,您仍然可以使用自己的CDN交付修改后的版本。 要遵循的主要准則是:
通常,您通常會發現,相對而言,您自己的服務器上的匹配次數實際上很少。 與往常一樣,不要相信我:在您自己的真實場景中保存統計信息!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.