0

I'm trying to defer a very simple jQuery test, in order to optimize the speed of my website:

This is the jQuery test:

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

It works correctly. However, if I change the call to the jQuery libraries:

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

it won't work.

Am I doing something wrong? Thank you.

4

1 回答 1

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>
于 2019-06-26T15:44:12.957 回答