如何使用JavaScript添加jQuery?

时间:2011-10-28 11:01:26

标签: javascript jquery

我试图有条件地将jQuery包含在HTML页面中。如果它还不存在,只需要添加它。

我在body标签顶部附近使用以下代码来注入一个包含头部jQuery库的脚本标记。

<script type="text/javascript">

    if (typeof jQuery === 'undefined') {
        alert('now adding jquery');
        var head = document.getElementsByTagName("head")[0];
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js';
        head.appendChild(script);
        if (typeof jQuery === 'undefined') {
            alert('jquery still not present :(');
        }
    } else {
        alert('jquery already present');
    }
</script>

当我执行它时,我得到的消息是jQuery在添加后仍然不存在。脚本标记 正确显示在已加载页面的源代码中。

尝试在我的页面中进一步使用jQuery,确认jQuery确实不起作用。正如预期的那样,Chrome的JavaScript控制台显示“$ not defined”。

我怎样才能让它发挥作用?

3 个答案:

答案 0 :(得分:2)

Boilerplate使用此方法测试jQuery是否由google加载,如果不使用local:

  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  <script>window.jQuery || document.write('<script src="js/libs/jquery-1.6.2.min.js"><\/script>')</script>

看起来像你想要实现的目标:)

答案 1 :(得分:2)

您不是在将脚本附加到文档

后等待加载

在追加之前尝试使用此代码:

   function helper(){
        if (typeof jQuery === 'undefined') {
            alert('jquery still not present :(');
        }
   };

   script.onreadystatechange= function () {
      if (this.readyState == 'complete') helper();
   }
   script.onload= helper;

如果你想了解更多

,我发现它here

还有像StealJS或YepNope

这样的加载器

答案 2 :(得分:2)

脚本异步加载。这意味着在追加元素后,其内容无法直接使用。

改为使用onload

script = document.createElement('script');

script.onload = function() {
    // jQuery is available now
};

script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js';

head.appendChild(script);