javascript - 避免动态加载 JavaScript 应用程序中的 jQuery 冲突

标签 javascript jquery conflict

我目前正在尝试开发一个可以嵌入现有网页(我无法修改)的 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);
})();

如果您有多个相互依赖的脚本,您可能需要尝试使用脚本加载器,例如 HeadJSLABjs .

如果您希望在管理依赖项方面具有更大的灵活性,您可以尝试使用模块加载器,例如 RequireJS , Browserify ,或webpack .

关于javascript - 避免动态加载 JavaScript 应用程序中的 jQuery 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23641224/

相关文章:

javascript - 使用 javascript 和/或 jquery 通信 HTTP 和 HTTPS 窗口

由于多个样式表导致 css 选择器特异性冲突

java - 无法在 Fedora 14 上安装 JDK 1.7

Maven:冲突的 jar 依赖项

javascript - 未捕获的类型错误 : Cannot read property 'find' of undefined

javascript - 如何使用 selenium 处理复式输入检查 java 脚本提示

javascript - Promise 返回 undefined

javascript - 对象 : null prototype does not allow to retrieve a value

java - 使页面的一部分在回发时保持完整

javascript - 在阅读方法文档时,参数周围的括号是什么意思?