简单的jQuery“ <脚本延迟”不起作用

时间:2019-06-26 15:23:37

标签: javascript jquery pagespeed deferred-loading

我正在尝试推迟一个非常简单的jQuery测试,以优化我的网站的速度:

这是jQuery测试:

<html>
  <head>
    <title>Test Defer</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
  </head>
  <body>
  <script type="text/javascript">$(document).ready(function(){$("#jquerytext").html("Hello World by JQuery");});</script>
  Hello World by HTML
  <div id="jquerytext"></div>
  </body>
</html>

它正常工作。但是,如果我将对jQuery库的调用更改为:

<script defer src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

它不起作用。

我做错什么了吗?谢谢。

1 个答案:

答案 0 :(得分:0)

正如漂亮的注释中正确指出的那样,它应该使用'window.onload'事件,因为它将在加载所有页面(包括延迟的脚本)后触发。

<html>
  <head>
    <title>Test Defer</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
  </head>
  <body>
  <script type="text/javascript">
     window.onload = function() {
      $(document).ready(function(){$("#jquerytext").html("Hello World by JQuery");});
     };
  </script>
  Hello World by HTML
  <div id="jquerytext"></div>
  </body>
</html>