让我们面对现实吧,jQuery/jQuery-ui 的下载量很大。
谷歌推荐JavaScript 的延迟加载 http://code.google.com/speed/page-speed/docs/payload.html#DeferLoadingJS以加快初始渲染速度。我的页面使用 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 代码未能找到 jQuery(对我来说并非完全出乎意料):
$(document).ready(function() {
$("#tabs").tabs();
});
所以,看来我需要找到一种方法来推迟 jQuery 代码的执行,直到加载 jQuery。如何检测添加的标签已完成加载和解析?
作为一个推论,似乎异步加载 http://code.google.com/speed/page-speed/docs/rtt.html#PreferAsyncResources也可能包含一个答案。
有什么想法吗?
试试这个,这是我不久前从 jQuerify 书签中编辑的内容。我经常使用它来加载 jQuery 并在加载后执行内容。当然,您可以将那里的 url 替换为您自己的自定义 jquery 的 url。
(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
})
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)