[英]How to detect if jquery has finished loading using javascript
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
Ok so I'm using googles tip to defer loading of jQuery and fix any Render-blocking
issue. 好的,所以我正在用Google的技巧来推迟jQuery的加载并解决任何Render-blocking
问题。
The issue happens when you are blocking external script during parsing
which is loading jQuery
or any other large javascript files
that is not needed to render the above-the-fold region. 当您blocking external script during parsing
(加载jQuery
或呈现上述首屏区域所需的任何其他large javascript files
,会发生此问题。 So with the code above the issue is fixed. 因此,上述代码已解决。 BUT I have one problem I have codes that run $(document).ready()
but it bugs up because jQuery hasn't loaded yet. 但是我有一个问题,我有运行$(document).ready()
代码,但是由于jQuery尚未加载而导致错误。
How do I find out if jQuery has finished loading? 如何确定jQuery是否已完成加载?
One option would be to put the script tag at the end of the body, or: 一种选择是将script标签放在正文的末尾,或者:
(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
});
})();
From this answer: https://stackoverflow.com/a/5853358/1766140 从这个答案: https : //stackoverflow.com/a/5853358/1766140
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.