简体   繁体   中英

Quick question about javascript (body-tag)

Does the page load faster if i use the javascript before the </body> tag? Example:

<body>

balbllb content

 <script type="text/javascript" src="jQuery.js"></script>
 <script type="text/javascript">
    $(function(){

    });
  </script>



</body>

The page will still load in the same amount of time, but it might be perceived as loading faster (ie you might see DOM element(s) appearing quicker).

If it was me, I would leave your jQuery.js reference in the <head> , and keep your custom stuff before the end of <body> .

I don't know whether it loads faster (I would be surprised) but in this case you no longer need to wrap your code in a $(document).ready as at that moment the document will be ready to be manipulated:

<body>
    balbllb content
    <script type="text/javascript" src="jQuery.js"></script>
    <script type="text/javascript">
        // directly manipulate the DOM here
    </script>
</body>

Its not about anything happening faster. Its the order in which things happen. Putting scripts at the bottom (right before the closing body tag) makes it so the rest of your content loads before loading the scripts, making it appear that its loading faster.

The total page load time will be the same. But the page will be perceived as loading faster since it will appear to the user faster. The "perception of loading faster" is not a conjecture, it is a fact, proven many times by psychologists.

Remember that if you load your JS libraries at the bottom of the page (as you should), then any dependent scripts must follow the libraries at the bottom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM