问题描述
我想在可以添加到随机网站的附加 JS 库中使用 jQuery.这些网站可能已经使用也可能不使用 jQuery.
I want to use jQuery in an add on JS library that can be added to random websites. These websites may or may not use jQuery already.
我实际上有 3 个问题:
I have 3 questions around this actually:
我可能会从我自己的 js 脚本(而不是从文档头中的脚本标签)动态加载 jQuery.jquery会以这种方式工作吗?在主文档中没有标准 $(document).ready(function(){} 的情况下,如何确保它及时运行?
I will probably load jQuery dynamically from my own js script (not from a script tag in the document head). Will jquery work this way? how can I make sure it will run in time without having the standard $(document).ready(function(){} in the main document?
我应该怎么做才能避免与网站代码中现有的 jQuery(如果有)发生冲突.
What should I do to avoid conflicts with existing jQuery (if any) in the web site code.
有没有推荐的方法来将包含 jQuery 的小部件添加到随机网站,同时提供最少的代码和最简单的集成.
Is there a recommended way to add a widget that includes jQuery to random websites while providing minimal code and simplest integration.
推荐答案
这是相当松散和不完整的——实际上是作为一个起点:
This is pretty loose and incomplete -- and really is meant to be a starting point:
if (typeof $ != 'undefined') {
var msg = 'This page already using jQuery v' + $.fn.jquery;
} else {
var s = document.createElement('script');
s.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js');
document.getElementsByTagName('head')[0].appendChild(s);
var msg = 'This page is now jQuerified';
}
然后在运行 ready() 函数之前通过一个简短的 setTimeout() 等待
then wait via a brief setTimeout() before running a ready() function
这篇关于小部件中的 jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!