This is the 11th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

What is the Web page lifecycle?

We browse related information through one TAB after another in the browser every day. When we open many tabs in the browser, the browser will not save resources for each page when the resources are tight. Instead, the browser will reallocate resources when the tabs are not active. Browser interference with these pages is exposed through the page lifecycle API. This life cycle is the main topic of our discussion.

The main events of the page life cycle

1. DOMContentLoaded

This API indicates that the browser has fully loaded the HTML and built the DOM tree, but external resources such as CSS and IMG have not yet been loaded. In this example, img is a resource from the CDN, not a local resource. If the local resource is requested, the size of the image can be obtained.

<h1>Hello, DOMContentLoaded!</h1>
<img id="img" src="https://en.js.cx/clipart/train.gif? speed=1&cache=0">

<script>
    function testReady() {
        alert('The DOM tree is built! ')
        alert('Now the size of the image is${img.offsetWidth}*${img.offsetHeight}`)}document.addEventListener('DOMContentLoaded',testReady);
</script>
Copy the code

CodeSandBox online demo

  • DOMContentLoaded waits for all script tags to execute before executing.
<script>
    document.addEventListener("DOMContentLoaded".() = > {
        alert("DOM ready!");
    });
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js"></script>

<script>
    alert("Library loaded, inline script executed");
</script>
Copy the code

The above code outputs the Library first… DOM Ready!

  • If a style resource is followed by a script tag, the style and the script tag must be executed before DOMContentLoaded is called.
<script>
    document.addEventListener("DOMContentLoaded".() = > {
        alert("DOM ready!");
    });
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js"></script>

<script>
    alert("Library loaded, inline script executed");
</script>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap-grid.css" rel="stylesheet">
<script>
  // The script is not executed until the stylesheet is loaded
  alert(getComputedStyle(document.body).marginTop);
</script>
Copy the code

2. window.onload

This event indicates that the page has loaded all the HTML, DOM trees, style images, and other resources.

<script>
    window.onload = function test() {
        alert('HTML, images, styles and other resources are loaded ');
        alert(The size of the picture is${img.offsetWidth}*${img.offsetHeight}`);
    }
</script>

<img id="img" src="https://en.js.cx/clipart/train.gif? speed=1&cache=0">
Copy the code

CodeSandBox online demo

3. window.unload

This event is triggered when the visitor leaves the page, and there are some things you can do here that don’t involve delay.

let analyticsData = { /* Object with collected data */ };

window.addEventListener("unload".function() {
  navigator.sendBeacon("/analytics".JSON.stringify(analyticsData));
});
Copy the code

4. window.beforeunload

This event will alert the user if the blade is about to close or jump.

<h1>Hello, DOMContentLoaded! </h1><a href="http://www.baidu.com">Click to jump to Baidu</a>

<script>
    window.addEventListener('beforeunload'.(event) = > {
        // Cancel the event as stated by the standard.
        event.preventDefault();
        // Chrome requires returnValue to be set.
        event.returnValue = 'Write something clever here.. ';
    });

</script>
Copy the code

CodeSandBox online demo

Determine if the document has been loaded: readyState

The API contains three states.

1. Loading (the document is loading)

2. Interactive (interactive, but some image resources and styles still loading)

3. Complete the loading of the document

console.log(The initialization state is:.document.readyState);

img.onload = () = > console.log('The image has been loaded');

document.addEventListener('DOMContentLoaded'.() = > console.log('DOMContentLoaded'))

document.addEventListener('readystatechange'.() = > console.log('Status changed to:'.document.readyState))

window.onload = () = > console.log('window onload');
Copy the code

CodeSandBox online demo

The resources

  • Page life cycle

  • MDN—document.readyState