The impact html page rendering And <script> location

Knock weekend overtime code used in the <script> tag, suddenly thought of a problem: another self-test project inside <script> I put him in a different position, there should be code execution and rendering after effects of it? So today carried out a special inquiry, took the opportunity to summarize the following:

    Interpreted html document & order:

        :( need prior knowledge to understand the difference between simple synchronous / asynchronous)                

              Synchronization, all operations are done before the results returned to the user. After that is finished database, the user, the user experience is not good.

              Asynchronous operation done without waiting for all the requests to the appropriate user. That is, first the user request, and then slowly to write database, the user experience better.

  1. Execution html document, from top to bottom explanation
  2. Interpretation encountered <link>, <img> tags will be asynchronously upload / download, and then continue down the interpreted code
  3. Instead encountered <script> tag, the case will start synchronization request JS file, and then stepping through the code in a JS file, and then finished to know all code execution proceeds remaining html code interpretation

   Effect <script> tag problems caused And position:

  • Solve the <script> synchronous execution blocking problems led to html script explains:
  1. A method => the <script> in <body> last part
  2. A <script> tag added defer attribute; usage:
    <Script of the type = "text / JavaScript" defer="defer"> 
    the defer action: attribute specifies whether to script execution delayed until the page loads up. (Note: limited IE browser; Refer => click here )
    Of course, there are drawbacks: If multiple JS script is not determined when the execution of the script sequence
  • effects of <script> location:
          Preliminaries :( browser workflow)
          parse html document into a DOM tree => CSS parse tree generated CSSDOM => CSSDOM tree and the DOM tree to form Rending Tree => Layout => Render
    • The <script> in <head> </ head> between it and preloaded before Home other code, can be achieved, for example: call ahead js file *
    • The <script> in <body> </ body> between, the page loaded run (note in position <body> </ body> is recommended here on the last)

summary:

    1. Inside the head, all of the function function only loads do not perform, then execution is after something triggers (if the initialization of variables will lead to error)
    2. Directly loaded and executed inside the body

 

Guess you like

Origin www.cnblogs.com/gamecc666/p/11751735.html