可能推迟加载jQuery?

让我们面对它,jQuery / jQuery-ui是一个沉重的下载。

Googlebuild议延期加载JavaScript以加速初始渲染速度。 我的页面使用jQuery来设置一些低页面上的标签(主要是初始视图),我想推迟jQuery,直到页面已经呈现。

Google的延期代码在页面加载之后,通过挂载到onLoad事件中,为DOM添加一个标签:

<script type="text/javascript"> // Add a script element as a child of the body function downloadJSAtOnload() { var element = document.createElement("script"); element.src = "deferredfunctions.js"; document.body.appendChild(element); } // Check for browser support of event handling capability if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload); else window.onload = downloadJSAtOnload; </script> 

我想推迟加载jQuery这种方式,但是当我尝试了我的jQuery代码未能findjQuery(不完全意外的我的部分):

 $(document).ready(function() { $("#tabs").tabs(); }); 

所以,似乎我需要find一种方法来推迟我的jQuery代码的执行,直到加载jQuery。 如何检测添加的标签已完成加载和parsing?

作为推论,似乎asynchronous加载也可能包含一个答案。

有什么想法吗?

试试这个,这是我刚刚从jQuerify书签编辑过的东西。 我经常使用它来加载jQuery并执行它的东西后,加载。 你当然可以用你自己的urlreplace那里的url到你定制的jquery。

 (function() { function getScript(url,success){  var script=document.createElement('script');  script.src=url;  var head=document.getElementsByTagName('head')[0],    done=false;  script.onload=script.onreadystatechange = function(){   if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {    done=true;    success();    script.onload = script.onreadystatechange = null;    head.removeChild(script);   }  };  head.appendChild(script); } getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){ // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS }); })(); 

我真的将jQuery和jQuery-UI整合到一个文件中,并使用一个url。 如果你真的想单独加载它们,只需链接getScripts:

 getScript('http://myurltojquery.js',function(){ getScript('http://myurltojqueryUI.js',function(){ //your tab code here }) }); 

因为这是一个关于重要议题的排名最高的问题,所以让我大胆地提出一个基于@valmarv和@amparsand的回答。

我正在使用multidimensional array来加载脚本。 将它们之间没有依赖关系的组合在一起:

 var dfLoadStatus = 0; var dfLoadFiles = [ ["http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"], ["http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js", "/js/somespecial.js", "/js/feedback-widget.js#2312195", "/js/nohover.js"] ]; function downloadJSAtOnload() { if (!dfLoadFiles.length) return; var dfGroup = dfLoadFiles.shift(); dfLoadStatus = 0; for(var i = 0; i<dfGroup.length; i++) { dfLoadStatus++; var element = document.createElement('script'); element.src = dfGroup[i]; element.onload = element.onreadystatechange = function() { if ( ! this.readyState || this.readyState == 'complete') { dfLoadStatus--; if (dfLoadStatus==0) downloadJSAtOnload(); } }; document.body.appendChild(element); } } if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload); else window.onload = downloadJSAtOnload; 

它加载第一个jquery后,加载它一次加载其他脚本。 您可以通过添加到页面上的任何位置的数组轻松地添加脚本:

 dfLoadFiles.push(["/js/loadbeforeA.js"]); dfLoadFiles.push(["/js/javascriptA.js", "/js/javascriptB.js"]); dfLoadFiles.push(["/js/loadafterB.js"]); 

把jQuery和你的jQuery相关的代码放在HTML文件的末尾。

编辑:更清楚一点

 <html> <head></head> <body> <!-- Your normal content here --> <script type="text/javascript" src="http://path/to/jquery/jquery.min.js"></script> <script>//Put your jQuery code here</script> </body> </html> 
 element.addEventListener("load", function () { $('#tabs').tabs() }, false); 

试试看

在某些情况下,你可以在jquery加载时触发一个事件。

 <script type="text/javascript"> (function (window) { window.jQueryHasLoaded = false; document.body.addEventListener('jqueryloaded', function (e) { console.log('jqueryloaded ' + new Date() ); }, false); function appendScript(script) { var tagS = document.createElement("script"), s = document.getElementsByTagName("script")[0]; tagS.src = script.src; s.parentNode.insertBefore(tagS, s); if ( script.id == 'jquery' ) { tagS.addEventListener('load', function (e) { window.jQueryHasLoaded = true; var jQueryLoaded = new Event('jqueryloaded'); document.body.dispatchEvent(jQueryLoaded); }, false); } } var scripts = [ { 'id': 'jquery', 'src': 'js/libs/jquery/jquery-2.0.3.min.js' }, { 'src': 'js/myscript1.js' }, { 'src': 'js/myscript2.js' } ]; for (var i=0; i < scripts.length; i++) { appendScript(scripts[i]); } }(window)); </script> 

然后将你的依赖包装在一个函数中:

 // myscript1.js (function(){ function initMyjQueryDependency() { console.log('my code is executed after jquery is loaded!'); // here my code that depends on jquery } if ( jQueryHasLoaded === true ) initMyjQueryDependency(); else document.body.addEventListener('jqueryloaded', initMyjQueryDependency, false); }()); 

如果jquery在其他脚本之后完成加载,那么当jqueryloaded事件被触发时,你的依赖将被执行。

如果jquery已经加载, jQueryHasLoaded === true ,那么你的依赖将会被执行initMyjQueryDependency()

这里是对async / defer javascript loading的现代方法的一个很好的描述。 但是它不适用于内联脚本

 <script type="text/javascript" src="/jquery/3.1.1-1/jquery.min.js" defer></script> <script type="text/javascript" defer> $(function () { // <- jquery is not yet initialized ... }); </script> 

asynchronous加载最简单的解决scheme是由@nilskp – externalize脚本build议的:

 <script type="text/javascript" src="/jquery/3.1.1-1/jquery.min.js" defer></script> <script type="text/javascript" src="resources/js/onload.js" defer></script> 

那么在我看来,所有你需要做的就是:a)将你想要加载的jQuery代码添加到jQuery文件的末尾,或者b)将它附加到downloadJSAtOnload函数中,如下所示:

 <script type="text/javascript"> // Add a script element as a child of the body function downloadJSAtOnload() { var element = document.createElement("script"); element.src = "deferredfunctions.js"; document.body.appendChild(element); $("#tabs").tabs(); // <==== NOTE THIS. This should theoretically run after the // script has been appended, though you'll have to test this // because I don't know if the JavaScript above will wait for // the script to load before continuing } // Check for browser support of event handling capability if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload); else window.onload = downloadJSAtOnload; </script> 

下面的代码应该在窗口加载完成后加载你的脚本:

 <html> <head> <script> var jQueryLoaded = false; function test() { var myScript = document.createElement('script'); myScript.type = 'text/javascript'; myScript.async = true; myScript.src = jQueryLoaded ? 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js' : 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js'; document.body.appendChild(myScript); if(!jQueryLoaded){ alert('jquery was loaded'); jQueryLoaded = true; test(); } else { alert('jqueryui was loaded'); } } if (window.addEventListener){ alert('window.addEventListener'); window.addEventListener("load", test, false); } else if (window.attachEvent){ alert('window.attachEvent'); window.attachEvent("onload", test); } else{ alert('window.onload'); window.onload = test; } </script> </head> <body> <p>Placeholder text goes here</p> </body> </html> 

在Chrome,FF和IE9中为我工作 – 让我知道是否有帮助

这是我的版本,它支持链接,以确保脚本是一个接一个地加载,基于&符的代码:

 var deferredJSFiles = ['jquery/jquery', 'file1', 'file2', 'file3']; function downloadJSAtOnload() { if (!deferredJSFiles.length) return; var deferredJSFile = deferredJSFiles.shift(); var element = document.createElement('script'); element.src = deferredJSFile.indexOf('http') == 0 ? deferredJSFile : '/js/' + deferredJSFile + '.js'; element.onload = element.onreadystatechange = function() { if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') downloadJSAtOnload(); }; document.body.appendChild(element); } if (window.addEventListener) window.addEventListener('load', downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent('onload', downloadJSAtOnload); else window.onload = downloadJSAtOnload; 
 <!doctype html> <html> <head> </head> <body> <p>If you click on the "Hide" button, I will disappear.</p> <button id="hide" >Hide</button> <button id="show" >Show</button> <script type="text/javascript"> function loadScript(url, callback) { var script = document.createElement("script") script.type = "text/javascript"; if (script.readyState) { //IE script.onreadystatechange = function() { if (script.readyState == "loaded" || script.readyState == "complete") { script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function() { callback(); }; } script.src = url; document.body.appendChild(script); } loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js", function() { //YAHOO.namespace("mystuff"); $("#show").click(function() { $("p").show(); }); $("#hide").click(function() { $("p").hide(); }); //more... }); </script> </body> </html> 

我认为Modernizr.load()在这里值得一提 – 它很好地处理了依赖加载

看来你只需要<script defer> : http : //www.w3schools.com/tags/att_script_defer.asp

看看jQuery.holdReady()

“保留或释放jQuery准备好的事件的执行”。 (jQuery 1.6+)

http://api.jquery.com/jQuery.holdReady/

我在async / defered jquery脚本标记之后添加了这段代码,这个代码定义了一个临时函数$,它会累积无论什么时候所有的东西都加载完成,然后一旦我们完成了这次使用$将被覆盖以执行function。 使用这段代码,不需要在文档中进一步更改jQuery onload语法。

 <script defer async src="jquery-2.2.0.min.js"> <script> var executeLater = []; function $(func) { executeLater.push(func); } window.addEventListener('load', function () { $(function () { for (var c = 0; c < executeLater.length; c++) { executeLater[c](); } }); }) </script> 

….接着…

 <script> $(function() { alert("loaded"); }); </script>