Loading sequence of HTML Web page

Hi everyone, I'm Hao, I love KFC.

Today I share about Loading sequence of a web page.




A. Basic flow:

Basic flow is below: 

1. Fetch the HTML page (e.g. index.html)

2. Begin parsing the HTML

3. Parse a <script> tag, or <style> tag, if have external file, download it.
* The parser blocks and stops parsing the other HTML on your page.

4. After the js script is downloaded, it execute, or CSS rules are parsed and defined

5. The parser continues parsing the rest of the HTML document.

B. Non-blocking load:

At step 3, it causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.

Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.

async

<script src="path/to/script1.js" async></script>
<script src="path/to/script2.js" async></script>

Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime. This implies that it's possible to script 2 is downloaded and executed before script 1.


defer

<script src="path/to/script1.js" defer></script>
<script src="path/to/script2.js" defer></script>

Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.

Unlike async scripts, defer scripts are only executed after the entire document has been loaded.

C. Run Javascript while Loading

If Parser block below part of HTML, so how we can execute JS code that refer to below (not load)??

Solution is simple:

1. Use DOMContentLoaded:

document.addEventListener("DOMContentLoaded", function() {
    // this function runs when the DOM is ready, i.e. when the document has been parsed
    document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});

2. Put JS code after HTML code:

<div id="mydiv">Hello World</div>
<script type="text/javascript">/* <![CDATA[ */
  alert($("#mydiv").html());
/* ]]> */</script>

3. Use $(window).ready

<script type="text/javascript">/* <![CDATA[ */
  $(window).ready(function(){
                    alert($("#mydiv").html());
                  });
/* ]]> */</script>
<div id="mydiv">Hello World</div>

4. Use async or defer

Nhận xét

  1. Lucky Club Casino Site | Online casino UK | Lucky Club
    Lucky Club is a UK online casino accepting UK players. Join us today to get your exclusive bonus & free spins. 카지노사이트luckclub Click here for more info.

    Trả lờiXóa

Đăng nhận xét