使用Javascript加载jQuery并使用jQuery


83

我使用以下方法将jQuery库附加到dom:

 var script = document.createElement('script');
 script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
 script.type = 'text/javascript';
 document.getElementsByTagName('head')[0].appendChild(script);

但是,当我运行时:

jQuery(document).ready(function(){...

控制台报告错误:

Uncaught ReferenceError: jQuery is not defined

如何动态加载jQuery,以及如何将其放入dom中使用它?


2
与更优化的方法相比,您是否有理由这样做?
代码Maverick

在这个问题的一些答案可以帮助你- stackoverflow.com/questions/7474354/...
mrtsherman

@斯科特是的。我有一个应用程序,在安装时它会同时加载jquery和脚本。我需要在脚本中加载jquery,以便jquery不会破坏用户主题。我需要有条件地将javascript加载到其主题内的某个网页上。请相信我。
ThomasReggi

jQuery为什么会破坏用户的主题?如果加载jQuery(对CSS没有影响)会破坏主题,则您所做的事情非常错误。
Anders Tornblad 2012年

很好,但是,如果他们使用的是旧版本的jQuery或其他库,该怎么办?
ThomasReggi

Answers:


138

这里有一个工作的JSFiddle,上面有一个小例子,它可以确切地说明您正在寻找什么(除非我误解了您的请求)http : //jsfiddle.net/9N7Z2/188/

这种动态加载javascript的方法存在一些问题。当涉及到非常基础的框架(如jQuery)时,您实际上可能想静态地加载它们,因为否则,您将必须编写一个完整的JavaScript加载框架...

您可以使用一些现有的JavaScript加载程序,也可以通过观察window.jQuery定义来编写自己的加载程序。

// Immediately-invoked function expression
(function() {
    // Load the script
    var script = document.createElement("SCRIPT");
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.type = 'text/javascript';
    script.onload = function() {
        var $ = window.jQuery;
        // Use $ here...
    };
    document.getElementsByTagName("head")[0].appendChild(script);
})();

请记住,如果您需要支持真正的旧浏览器(如IE8),load则不会执行事件处理程序。在这种情况下,您将需要轮询是否存在window.jQuery使用repeat window.setTimeout。这里有一个使用该方法的有效JSFiddle:http : //jsfiddle.net/9N7Z2/3/

很多人已经完成了您需要做的事情。查看一些现有的JavaScript Loader框架,例如:


此解决方案有效,WordPress中除外。可以通过任何方式将jQuery加载到其他对象中吗?
Kraang Prime

@SanuelJackson对于Wordpress,您应该使用该wp_enqueue_script()函数正确地包含jQuery。文档:codex.wordpress.org/Function_Reference/wp_enqueue_script此处提供更多信息:digwp.com/2009/06/include-jquery-in-wordpress-the-right-way或此处:digwp.com/2011/09/using-代替jquery-in-wordpress
Anders Tornblad 2014年

是的,我的意思是上面的代码在Wordpress上不起作用,因为它也会异步加载jQuery。即使此脚本加载在页面的最底部(恰好在关闭html之前),jQuery也没有完全“初始化”,因此它看不到jQuery加载,并继续加载并执行回调。一旦加载,它会错误地依赖异步加载的其他东西,这些东西依赖于jQuery以不同的方式加载(例如$,jQuery等),或者依赖于不同版本的jQuery。
Kraang Prime

在我尝试过的其他情况下,这很棒。只是在记下与此有关的唯一明显问题。如果以某种方式可以对其进行调整,但我认为这是不可能的,因为它取决于检测jQuery,这当然不会被加载,因此只能以-如果没有jquery ... then ..的逻辑进行。
Kraang Prime

1
您无需进行轮询,只可以使用一行等待直到使用.onload事件(如stackoverflow.com/a/42013269/3577695)
aljgom

7

还有另一种动态加载jQuery的方法()。您也可以使用

document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>');

使用该方法被认为是不好的做法document.write,但是为了完整起见,值得一提。

请参阅为什么document.write被认为是“不良做法”?原因。该document.write不加载其他资产产生阻止你的页面,所以没有必要创建一个回调函数。


1
我阅读了您链接到的文档,并且对于为IE8加载旧版jQuery库的用例,使用document.write似乎还可以。到目前为止,对我来说效果很好。
艾伦

这是最简单,最直接的方法。在一个较大的脚本(一个单独的JS文件)的开头执行此操作是否会出现问题?太好了,无法通过。
奥古斯丁·拉多

6

Encosia的网站建议:

<script type="text/javascript" 
        src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  // You may specify partial version numbers, such as "1" or "1.3",
  //  with the same result. Doing so will automatically load the 
  //  latest version matching that partial revision pattern 
  //  (e.g. 1.3 would load 1.3.2 today and 1 would load 1.7.2).
  google.load("jquery", "1.7.2");

  google.setOnLoadCallback(function() {
    // Place init code here instead of $(document).ready()
  });
</script>

但是即使他也承认,就最佳性能而言,这与做以下事情没有区别:

    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script type="text/javascript"> window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js">\x3C/script>')</script>
    <script type="text/javascript" src="scripts.js"></scripts>
</body>
</html>

我只能加载一个JavaScript。这意味着我必须先动态加载Google jsapi,然后再从该加载jquery中加载?对于我的用例来说似乎多余。
ThomasReggi

1
这就是jQuery加载程序的作用。您引用加载程序,然后加载程序将jQuery注入到您的文档中。
Code Maverick

3

您需要在jQuery完成加载后运行代码

var script = document.createElement('script'); 
document.head.appendChild(script);    
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = function(){
    // your jQuery code here
} 

或者如果您正在异步函数中运行它,则可以await在上面的代码中使用

var script = document.createElement('script'); 
document.head.appendChild(script);    
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
// your jQuery code here

如果要首先检查页面中是否已经存在jQuery,请尝试此操作


0

出现此错误的原因是JavaScript不等待脚本加载,因此在运行时

jQuery(document).ready(function(){...

不能保证脚本已准备就绪(永远不会)。

这不是最优雅的解决方案,但可行。基本上,您可以每1秒检查一次jQuery对象广告在加载了您的代码后是否运行了该函数。我还要添加一个超时(在运行20次后再说一次clearTimeout),以阻止检查无限期地发生。

var jQueryIsReady = function(){
    //Your JQuery code here
}

var checkJquery = function(){
    if(typeof jQuery === "undefined"){
        return false;
    }else{
        clearTimeout(interval);
        jQueryIsReady();
    }
}
var interval = setInterval(checkJquery,1000);

0

使用require.js可以更安全地执行相同的操作。您可以只定义对jquery的依赖关系,然后在加载依赖关系时使用所需的代码,而不会污染名称空间:

我通常建议使用此库来管理对Javascript的所有依赖关系。它很简单,可以有效地优化资源加载。但是,将其与JQuery结合使用时,可能需要采取一些预防措施。我最喜欢的处理它们的方法在此github存储库中进行了解释,并通过以下代码示例得到反映:

<title>jQuery+RequireJS Sample Page</title>
   <script src="scripts/require.js"></script>
   <script>
   require({
       baseUrl: 'scripts',
       paths: {
           jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min'
       },
       priority: ['jquery']
    }, ['main']);
    </script>

0

HTML:

<html>
  <head>

  </head>
  <body>

    <div id='status'>jQuery is not loaded yet.</div>
    <input type='button' value='Click here to load it.' onclick='load()' />

  </body>
</html>   

脚本:

   <script>

        load = function() {
          load.getScript("jquery-1.7.2.js");
          load.tryReady(0); // We will write this function later. It's responsible for waiting until jQuery loads before using it.
        }

        // dynamically load any javascript file.
        load.getScript = function(filename) {
          var script = document.createElement('script')
          script.setAttribute("type","text/javascript")
          script.setAttribute("src", filename)
          if (typeof script!="undefined")
          document.getElementsByTagName("head")[0].appendChild(script)
        }

        </script>

困难的部分是在脚本加载运行脚本...为什么脚本始终未定义!
Anders Tornblad

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.