The method by which the browser loads JS

Speaking of which, the most common ones are built-in JS and external JS

Built-in:

<script>
console.log('Load complete')
</script>
Copy the code

Communications:

<script src="" type="application/javascript"></script>
Copy the code

Later, since the browser’s default scripting language is JavaScript, the type attribute can be removed.

<script src=""></script>
Copy the code

Browser rendering rules

The browser’s rendering rule is that it loads from top to bottom and normally executes as soon as it loads.

CSS files can be rendered while loading, whereas JS files must wait until loading is complete.

If large JS files are encountered in the loading process, rendering will continue until JS is finished, blocking the loading of the entire page.

Asynchronous loading of the browser

To solve the load blocking problem, the browser provides the defer and Async properties.

So what’s the difference between defer and Async?

Add the defer attribute to the script tag, and its internal JS will not be executed until the entire page has loaded. This load includes rendering of the entire page and execution of other scripts. When there are multiple defers, they are executed in sequence.

With async, JS executes after the script tag is loaded. Once the load is complete, the rendering is interrupted to execute. Continue rendering after execution. Since the loading speed is uncertain, there is no guarantee of execution order between multiple Async scripts.

Browser ES6 module support

In ES6, add JS modular standard, add type=”module” on the script tag can be declared as ES6 module.

<script type="module" src=""></script>
Copy the code

For tags with type=”module” added, the browser defaults to defer until the entire page has loaded, or you can add the async tag, which will be executed after loading.

<script type="module" src="" async></script>
Copy the code

Also, tags with type=”module” can be embedded directly, so that the browser will load as the default.

<script type="module">
    import moduleA from './moduleA.js'
	console.log('Load complete')
</script>
Copy the code