如何在单个js文件中包含jQuery库而不干扰现有库 [英] How to include jQuery library in single js file without interfering with existing libraries
问题描述
第三方网站可以将我的脚本标签放置在其网站上,例如在头部中的ExternalSite.html等:
3rd party websites can place my script tag on their websites, like so on for example ExternalSite.html in the head section:
<script type="text/javascript">
(function () {
var ttScript = document.createElement('script'); ttScript.async = true;
ttScript.src = '//www.example.com/script/myscript.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>
在我自己的服务器上,文件myscript.js中包含以下代码:
On my own server, in the file myscript.js I have this code:
$.ajax({
url: "http://www.example.com/iplookup.php",
data: null,
type: 'GET',
crossDomain: true,
dataType: 'jsonp'
}).done(function (json) {
self.ip = json;
});
但是,一旦用户访问了第三方网站,在第一行我会得到Uncaught ReferenceError: $ is not defined
But once a user visits the 3rd party site, on the first line here I get Uncaught ReferenceError: $ is not defined
现在,这可能是因为我没有在第三方网站上引用jQuery,而是在其中包含myscript.js文件.问题是:
Now this is probably because I don't reference jQuery on the 3rd party site, where I include the myscript.js file. The problem is that:
- 我不知道这个第三方网站是否甚至正在运行jQuery
- 我不知道如何从myscript.js引用jQuery,也不会干扰第三方网站上现有的jQuery引用
推荐答案
首先进行检查 使用javaScript进行jQuery加载
First make a check for jQuery load using javaScript
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
// Now insert your scripts
} else {
// jQuery is not loaded
// Load it manually from any cdn e.g., //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
}
}
我们可以使用其他一些类似的检查方式
There are some other similar ways of checking which we can use
if (typeof jQuery != 'undefined') {
// jQuery is loaded
} else {
// jQuery is not loaded
}
if (jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}
atornblad 提供了一个有效的 fiddle
告诉jQuery加载所需的时间.
There 's a working fiddle
available by atornblad which also tells the time jQuery took to load.
您可以寻求更好的参考.
You can have a look for a better reference.
希望这会有所帮助.
这篇关于如何在单个js文件中包含jQuery库而不干扰现有库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!