如何使用JavaScript添加jQuery?

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

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

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

当我执行它时,我得到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:

    

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

您不是在将脚本附加到文档后等待加载脚本

在添加之前尝试此代码:

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

如果你想了解更多,我在这里找到了它

还有像StealJS或YepNope这样的加载器