我如何添加jQuery头部与JavaScript

How Do I Add jQuery To Head With JavaScript?

本文关键字:jQuery 头部 JavaScript 添加 何添加      更新时间:2023-09-26

我试图有条件地将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"。

我怎样才能使它工作?

脚本异步加载。这意味着在附加元素之后,它的内容不能直接使用。

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);

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>

似乎是你想要实现的:)

在将脚本追加到文档

后,不需要等待脚本加载

在附加之前试试下面的代码:

   function helper(){
        if (typeof jQuery === 'undefined') {
            alert('jquery still not present :(');
        }
   };
   script.onreadystatechange= function () {
      if (this.readyState == 'complete') helper();
   }
   script.onload= helper;

如果你想知道更多,我在这里找到了

也有加载器像StealJS或YepNope