Does the [removed] tag position in HTML affects performance of the webpage?

前端 未结 8 1084
清酒与你
清酒与你 2020-11-29 19:39

If the script tag is above or below the body in a HTML page, does it matter for the performance of a website?

And what if used in between like this:

         


        
8条回答
  •  暖寄归人
    2020-11-29 20:20

    Firstly script tags not inside body/head elements create invalid HTML and might even cause some exceptions in some browsers.

    Script tags inside the head element will be loaded and interpreted before any HTML is rendered, this blocks HTML/CSS rendering.

    Script tags at the bottom of the body tag, will not block HTML/CSS and since you can only play around with the DOM on DomReady, this is the best position to put your JavaScript. As a side note, you won't even need to use a domReady event wrapper.

    Alternatively, you can also use libraries like LABJS and RequireJS to kickstart your JavaScript from the head tag (minimal HTML/CSS blocking). Any scripts loaded through either of these libraries will run in paralel to HTML/CSS rendering.

    
       
    
    

    INITSCRIPT.js

    require( [ "jQuery" , "somePlugin" ] , function(){
       $(document).ready(function(){
          $("#someId").somePlugin();   
       });
    } );
    

    In the above example, only the load and interpretation of require.js will block HTML/CSS rendering, which usually is insignificant. After which jQuery and somePlugin will be loaded in paralel, so HTML/CSS renders just nicely.

提交回复
热议问题