Which is the load, rendering and execution order of elements in a HTML page?

后端 未结 1 1659
轻奢々
轻奢々 2020-12-15 09:50

I found this nice post at kirupa.com, but I\'d like to understand in deep the order of load, rendering and execution of elements like DOM, Scripts, CSS, Images, IFrames, etc

相关标签:
1条回答
  • 2020-12-15 10:34

    I believe the order is something like this:

    1. Download HTML document
    2. Start HTML Parsing
    3. Start downloading external files (JavaScript, CSS, images) as they're encountered in the HTML
    4. Parse external files once they are downloaded (or if they are inline and don't require downloading)
      • if the files are scripts, then run them in the order they appear in the HTML
        • if they try to access the DOM right now, they will throw an error
        • while they run, they will prevent any other rendering, which is why some scripts are put at the bottom of the body
      • for CSS files, save the style rules in order they appear in the HTML
      • if they're images then display them
      • if the loading fails, then proceed without this file
    5. End HTML Parsing
    6. Create the DOM - including all the styles we have so far
    7. Execute the DOMContentLoaded event when the DOM is fully constructed and scripts are loaded and run
      • happens even if all other external files (images, css) are not done downloading (from step 4)
      • in the Chrome F12 developer tools this is represented by a blue line on the Network view
      • will start running anything you've added to this event, e.g. window.addEventListener("DOMContentLoaded", doStuff, true);
    8. Start painting the document to the display window (with any styles that have already loaded)
    9. Execute the window.onload event when all external files have loaded
      • in the Chrome F12 developer tools this is represented by a red line on the Network view
      • this will start running the jQuery ready function $(document).ready(function(){ ... });
      • will start running any code you've added to this event, e.g. window.addEventListener("load", doStuff, true);
    10. Re-paint the document, including any new images and styles

    Note that the execution order of scripts that are dynamically added to your page (by other scripts) is complicated and basically indeterminate. (See the answers here load and execute order of scripts)

    0 讨论(0)
提交回复
热议问题