【问题标题】:How to make sure $(document).ready run after jQuery.js is available?如何确保 $(document).ready 在 jQuery.js 可用后运行?
【发布时间】:2011-07-20 17:48:20
【问题描述】:

在某些情况下,由于下载速度或其他异步问题,即使我在包含 jquery.js 后添加了$(document).ready(),有时我也会收到关于$ 是undefined 的抱怨。呸呸呸呸。

我不想那样做:

setTimeout(function() {$(document).ready()... }, 1000);

这看起来很蹩脚。

那么,有没有一种聪明的方法或正确的方法或好的方法来确保 document.ready 真的准备好被调用了? :)

【问题讨论】:

  • 在调用此函数之前,您是否在页面中包含了 jQuery? 100% 确定? ;-)
  • 在我调用 jquery 函数之前。但是,由于其他页面要求,它不在 中。它在调用它之前包含在正文中。
  • 我更喜欢使用 $(window).on('load', function(){//your code here}。只有当所有资产都可用时才会触发 load 事件,包括 jquery。

标签: jquery document-ready


【解决方案1】:

Denis 提供了一个很好的解决方案的链接。我现在正在使用它。

JavaScript - How do I make sure a jQuery is loaded?

请参阅链接中的答案和解释。

解决办法是:

<script type='text/javascript'>
runScript();

function runScript() {
    // Script that does something and depends on jQuery being there.
    if( window.$ ) {
        // do your action that depends on jQuery.
    } else {
        // wait 50 milliseconds and try again.
        window.setTimeout( runScript, 50 );
    }
}
</script>

【讨论】:

    【解决方案2】:

    我认为这实际上是不可能的,(事实上$ 将是undefined),文档头同步加载意味着每一行在下一行之前都已完全加载

    这里有一个视频,这个确切的测试被放在了测试中,看来我是对的

    视频:http://www.bennadel.com/blog/1915-How-Javascript-Loading-And-Blocking-Works-By-Default.htm

    您是否正确加载文件,例如

    <!DOCTYPE html>
    <html>
        <head>
            <title>...</title>
            <script type="text/javascript" src="...."></script>
            <script type="text/javascript" src="...."></script>
            <script type="text/javascript" src="...."></script>
            <script type="text/javascript" src="...."></script>
            <script type="text/javascript">
                jQuery.ready(function(){
                   //This is executed once all 4 above have been loaded
                });
            </script>
            <script type="text/javascript" src="...."></script>
            <script type="text/javascript" src="...."></script>
            <!-- The above to scripts are loaded in order after the jquery function has run. -->
        </head>
    </html>
    

    jQuery 的ready 方法only 会在hole 文档被加载后被触发,直到DOM 看到最后的结束标记,通常是&lt;/html&gt; [需要引用]

    虽然说不可能,但在IE8或更低版本可能有可能,原因是IE可能是有史以来最糟糕的浏览器,但他们说IE9已经彻底大修,应该满足于喜欢Google、Apple、Mozilla 等

    如果您使用多个库或覆盖 $ 变量,您可以在锁定范围内获取它,如下所示:

    (function($){
        $.ready(function(){
            //Do your jQuery here !
        });
    })(jQuery)
    

    【讨论】:

    • 为什么投反对票,至少有礼貌地解释什么是不正确的?
    【解决方案3】:

    你可以通过doing来检查jQuery是否被加载。

    if (typeof jQuery !== 'undefined') {
      //do whatever here
    }
    

    您不必这样做。最好将所有 JavaScript 包含在 HTML 末尾和 &lt;/body&gt; 之前,首先是 jQuery。这是雅虎推荐的方法。您可以在http://developer.yahoo.com/performance/rules.html 阅读更多内容。这不会减慢您的页面加载速度,也不会给您带来未定义 jQuery 的问题。

    【讨论】:

      猜你喜欢
      • 2011-09-07
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 2014-04-20
      • 2017-09-13
      • 2012-07-28
      相关资源
      最近更新 更多