【问题标题】:How to check jquery already loaded or not?can we replace older version with new version programmatically?如何检查 jquery 是否已加载?我们可以以编程方式将旧版本替换为新版本吗?
【发布时间】:2013-05-25 22:20:09
【问题描述】:

我想知道,当我在页面中添加 jquery 时,我想在添加之前检查该 jquery 是否已添加,如果未添加则仅添加 else 不添加。

例如我添加了 jquery jquery-1.4.1.min

<script type="text/javascript" src="<?php echo SITE_JS;?>jquery-1.4.1.min"></script>

之后当我尝试添加 jquery jquery-1.7.1.min

in case i didnt know that i have already added or not 所以我尝试添加它,但在此之前我想检查版本,如果 jquery 与旧版本或相同,那么我不希望它添加,否则添加新 jquery 并禁用旧版本。

<script type="text/javascript" src="<?php echo SITE_JS;?>jquery-1.7.1.min"></script>

在添加之前,我想检查 jquery 是否已经存在更高版本。 怎么可能?

【问题讨论】:

  • 但是如何检查它是否已经存在?
  • window.jQuery 但不仅仅是全局变量 jQuery,如果未定义返回错误
  • 您以错误的方式解决依赖问题。这不是代码问题,而是依赖问题。解决根本原因,而不仅仅是症状。

标签: jquery conditional-statements exists


【解决方案1】:

试试看,

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="<?php echo SITE_JS;?>/jquery-1.9.1.min.js"><\/script>');
 // you should have jquery-1.9.1.min.js on the site url
</script>

【讨论】:

  • 不错的答案 +1 fr this and in this case.. 如何检查更高版本
  • @RohanKumar 如何禁用已加载的先前版本的 jquery
  • 看看这个解决你的问题stackoverflow.com/questions/10915263/…
【解决方案2】:

试试这个方法来检查jquery是否被加载...如果加载打印版本...

if (typeof jQuery != 'undefined') {  
        // jQuery is loaded => print the version
          alert(jQuery.fn.jquery);}

根据版本写一个逻辑来加载你的jquery版本...

【讨论】:

    【解决方案3】:

    使用“window.load”事件

    (function() {
    if (window.addEventListener) {
        // Standard
        window.addEventListener('load', jQueryCheck, false);
    }
    else if (window.attachEvent) {
        // Microsoft
        window.attachEvent('onload', jQueryCheck);
    }
    function jQueryCheck() {
        if (typeof jQuery === "undefined") {
            // No one's loaded it; either load it or do without
        }
    }
    })();
    

    Ref

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 2015-07-27
      • 2021-05-03
      • 2017-06-23
      相关资源
      最近更新 更多