【问题标题】:$(document).ready is not working when i put jquery library before body当我将 jquery 库放在正文之前时,$(document).ready 不起作用
【发布时间】:2013-10-20 00:23:45
【问题描述】:

它正在工作

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").slideToggle();
  });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<button>Toggle between slide up and slide down for a p element</button>

</body>
</html>

但是当我移动时

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

&lt;body&gt; 之前的标签不起作用,因为我想把 JavaScript 放在底部,但是我不能把 document.ready 部分放在 jquery 库之后,有什么解决办法。

【问题讨论】:

  • 你的代码应该可以工作,不管它在哪里,只要它在 jquery 库之后。
  • @Kierchon:我想把 JavaScript 放在底部,但是 document.ready 部分来自 cms
  • 我明白.. 我的问题是你为什么要把它放在底部?
  • 在 CMS 系统的情况下,通常最好将其保留在顶部,除非您在 CMS 中构建一种方法,使其包含底部的所有脚本,而不仅仅是库。
  • 那么我想是时候将它构建到您的 cms 中了,或者向您的老板解释这样做的利弊。

标签: javascript jquery optimization


【解决方案1】:

一:您的代码必须在 jquery 库之后。

二:如果将代码移到页面底部,则不需要$(document).ready(...

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>This is a paragraph.</p>
<button>Toggle between slide up and slide down for a p element</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("button").click(function(){
  $("p").slideToggle();
});
</script>
</body>
</html>

如果您绝对必须将您的页面特定代码放在 jquery 库之上,您可能需要一个队列系统,以便在 jquery 可用时处理队列。下面是一个例子

<!DOCTYPE html>
<html>

    <head>
        <!-- this would need to be part of the CMS header -->
        <script>
            window.initQueue = [];
        </script>

        <!-- here's your page specific js -->
        <script>
            window.initQueue.push(function(){
                $("button").click(function() {
                    $("p").slideToggle();
                });
            })
        </script>
    </head>

    <body>
        <p>This is a paragraph.</p>
        <button>Toggle between slide up and slide down for a p element</button>


        <!-- cms footer -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
            $.each(window.initQueue,function(i,fn){
                fn();
            })
        </script>
    </body>
</html>

【讨论】:

  • 如果 Op 想要放置脚本,为什么 OP 不能使用 window.onload 而不是 document.ready。虽然它不需要,因为它位于元素之后。
  • 他绝对可以。我不知道你为什么会这样问。
  • 我问是因为你的#1
  • 没错,总有“另一种方式”,即使它很糟糕。
  • 我的意思是,它并没有那么糟糕,但如果应用程序资产繁重,它实际上可能会对应用程序的性能产生负面影响。
【解决方案2】:
<script>
  window.onload = function() {
    $("button").click(function() {
       $("p").slideToggle();
    });
}

</script>

【讨论】:

  • @ParnitaDas 当然,将您的脚本设为外部,并使用 defer 属性。但请注意,它不适用于所有浏览器。
  • @ParnitaDas 我指的是您的评论,而不是这个答案。这个答案适用于所有浏览器,只是它必须等待所有资产加载(所有图像、css 工作表、css 引用的图像等),然后再执行您的 javascript。
猜你喜欢
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多