我目前正在尝试开发一个可以嵌入现有网页(我无法修改)的 JavaScript 应用程序。该应用程序需要特定版本的 jQuery。
用于加载应用程序的脚本执行以下操作:
// loading JavaScript needed by my application
(function () {
document.write('<script src="../jquery-1.10.2.min.js"></script>');
document.write(...); // load other scripts (using jQuery 1.10.2)
// storing the application's jQuery in a new namespace
// to avoid conflicts with other jQuery versions
document.write('<script type="text/javascript">' +
'appJQ = jQuery.noConflict(true);</script>'); // error: jQuery is undefined in IE<10
})();
// initializing the application itself
document.onload = function() {
// ...
};
这在我测试过的每个浏览器中都运行良好,除了 IE < 10。在 IE 9 及更低版本中,我收到 jQuery 未定义的错误。
将 jQuery 移动到 document.onload
函数中的新命名空间适用于我的应用程序,但如果它们需要不同版本的 jQuery,则会与包含我的应用程序的网页上的其他脚本发生冲突。
您对如何解决这个问题有什么建议吗? 感谢您的帮助!
最佳答案
而不是使用 document.write
,尝试创建一个 <script>
元素并为该元素定义 onload 处理程序:
(function () {
var script = document.createElement('script');
script.src = '//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js';
script.onload = function() {
var appJQ = jQuery.noConflict(true);
// app initialization code
};
var head = document.head || document.getElementsByTagName('head')[0];
head.appendChild(script);
})();
如果您有多个相互依赖的脚本,您可能需要尝试使用脚本加载器,例如 HeadJS或LABjs .
如果您希望在管理依赖项方面具有更大的灵活性,您可以尝试使用模块加载器,例如 RequireJS , Browserify ,或webpack .
关于javascript - 避免动态加载 JavaScript 应用程序中的 jQuery 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23641224/