99m*_*les 3 javascript jquery jquery-ui google-ajax-libraries
我正在制作一个由一段代码组成的小部件,用于放入您的网站,然后通过 js 获取内容。这是一个示例片段:
<div data-token="bc1cea6304e8" id="my-widget">
<script src="http://localhost:8080/assets/eg-widget.js" type="text/javascript"></script>
</div>
Run Code Online (Sandbox Code Playgroud)
我正在做一个测试,检查页面是否已经有 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();
}
Run Code Online (Sandbox Code Playgroud)
在任何一种情况下,我们都会为我们决定使用的 jQuery 设置一个变量 jQueryEg,以便我们可以避免冲突。
如果 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();
};
}
Run Code Online (Sandbox Code Playgroud)
一旦我遇到类似的问题。查看 jQuery-UI 代码,我注意到它都包含在一个立即调用的函数表达式中(或者我自己包装了它?我不记得了):
( function ( jQuery, undefined ){
// Code here...
})( jQuery );
Run Code Online (Sandbox Code Playgroud)
创建私有范围。所以我的解决方案是
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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2920 次 |
最近记录: |