preface

Hi, I’m Hui Ye and I’m so cute.

In the previous article, we outlined the browser rendering process. However, parsing HTML documents can be complicated. So we specifically pulled it out.

First, the meaning of loading: download + execute.

CSS

1. CSS files are downloaded in parallel

2. CSS does not block buildsThe DOM tree

3. The CSS download does not block the subsequent JS download, but the JS download will be blocked

However, CSS loading affects the execution of JS code, which I found surprising at first. Let’s take a look at an example:

To test this, you can set the Internet speed of Google Chrome

<! DOCTYPEhtml>
<html lang="en">
<head>
    <title>The CSS block</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script>
        alert('The document is parsed! ');
    </script>
    <link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.6/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<h1>This is red</h1>
</body>
<script>
    alert('Document parsing is over! ');
</script>
</html>
Copy the code

The document is parsed from the top down by executing alert(‘ The document is parsed! ‘); Then, the link tag is encountered and the outer chain CSS is loaded until the load is complete. The following alert(‘ Document parsing is over! ‘); .

This is because JS may fetch or change the style of the element, so the browser will execute the following JS sequentially, after the CSS above is loaded and parsed.

JS

  1. Modern browsers load JS files in parallel, but execute the code in written order

  2. Loading or executing JS blocks building the DOM tree, and the browser does not continue parsing the DOM until the JS execution is complete. Without the DOM tree, the browser can’t render, so when you load a large JS file, you can see the page blank for a long time.

This is because the loaded JS may create or delete nodes, etc., which will affect the DOM tree. If it is not blocked, JS modifies some nodes after the browser has parsed the tags to generate the DOM tree, and the browser has to re-parse and regenerate the DOM tree, which has poor performance.

If you don’t want JS to block your DOM tree generation, there are methods.

defer / async

Defer and Async are both applied to outchain JS. It has no effect on internal JS.

Both defer and Async are asynchronous; the main differences are in the order and time of execution.

Async flag script files will be executed immediately once loaded, and not in written order, who downloaded directly executed. Therefore, it is suitable for script files that have no code dependent order and no DOM manipulation.

The script files for the defer flag are executed in strict written order and before the DOMContentLoaded event (when the DOM of the page is loaded). This works with script files that have DOM operations or code dependent order.