Javascript non-blocking scripts, why don't simply put all scripts before </body> tag?

前端 未结 3 1948
渐次进展
渐次进展 2020-12-31 09:04

In order to avoid javascript to block webpage rendering, can\'t we just put all all our JS files/code to be loaded/executed simply before the closing

3条回答
  •  独厮守ぢ
    2020-12-31 09:56

    If you want asynchonous scripts. Use the (HTML5) async tag if it is availble in the browser you're in. This is what Google Analytics is doing in the code you posted (specifically the line ga.async = true MDN Link, scroll down for async).

    However, this can cause your script to load at arbitrary times during the page load - which might be undesirable. It's worth asking yourself the following questions before choosing to use async.

    Don't need user input? Then using the async attribute.

    Need to respond to buttons or navigation? Then you need to put them at the top of the page (in head) and not use the async tag.

    Async scripts run in any order, so if your script is depending on (say) jQuery, and jQuery is loaded in another tag, your script might run before the jQuery script does - resulting in errors.


    Why don't people put things at the bottom of the body tag? If the script is taking enough time to load that it's slowing/pausing the load of the website, it's quite possible that that script is going to pause/hang the website after the website has loaded (expect different behaviour on different browsers) - making your website appear unresponsive (click on a button and nothing happens). In most cases this is not ideal, which is why the async attribute was invented.


    Alternatively if your script is taking a long time to load - you might want to (after testing) minify and concatenate your script before sending it up to the server.

    I recommend using require.js for minifying and concatenation, it's easy to get running and to use.

    Minifying reduces the amount of data that needs to be downloaded.

    Concatenating scripts reduces the number of "round-trips" to the server (for a far away server with 200ms ping, 5 requests takes 1 second).

提交回复
热议问题