Let's face it, jQuery/jQuery-ui is a heavy download.

谷歌建议使用deferred loading of JavaScript来加速初始渲染.我的页面使用jQuery设置一些选项卡,这些选项卡放在页面的较低位置(大部分在初始视图之外),我希望将jQuery推迟到页面呈现之后.

Google's deferral code adds a tag to the DOM after the page loads by hooking into the body onLoad event:

<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>

I'd like to defer loading of jQuery this way, but when I tried it my jQuery code failed to find jQuery (not completely unexpected on my part):

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

所以,我似乎需要找到一种方法,将jQuery代码的执行推迟到jQuery加载之后.如何检测添加的标记已完成加载和解析?

作为推论,似乎asynchronous loading也可能包含答案.

有什么 idea 吗?

推荐答案

Try this, which is something I edited a while ago from the jQuerify bookmarklet. I use it frequently to load jQuery and execute stuff after it's loaded. You can of course replace the url there with your own url to your customized 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.如果您真的想单独加载它们,只需链接GetScript:

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

Jquery相关问答推荐

使用jquery ui来回滑动切换

如何在 jquery 中切换 attr()

Jquery如何通过数组中的属性查找对象

在 JavaScript 中解析 URL

使用 jQuery 更改 CSS 类属性

用按钮切换显示/隐藏div?

jQuery.parseJSON 与 JSON.parse

禁用 Android 网页中输入焦点的zoom

我可以将 Nuget 保留在 jQuery 1.9.x/1.x 路径上(而不是升级到 2.x)吗?

jquery:更改URL地址而不重定向?

我想了解 jQuery 插件语法

禁用 jquery Select 的下拉菜单

获取没有在css中设置高度的div的高度

如何使用 JQuery 获取 GET 和 POST 变量?

在未实现接口 FormData 的对象上调用附加

Uncaught TypeError: undefined is not a function on loading jquery-min.js

jQuery 发送字符串作为 POST 参数

在 jquery 中使用 AJAX Post 从强类型 MVC3 视图传递模型的正确方法

获取jQuery中下拉列表的值

小于 10 给数字加 0