📜 ⬆️ ⬇️

Download scripts in WebKit

The nightly version of WebKit now supports the async and defer properties of the script tag, which appeared in HTML5. Thus, the page loading speed increases as both the loading of scripts and the rendering of the page occur simultaneously.

As usual, the page is loaded: the parser scans the code for links to scripts, and if they are detected, the script starts loading, and parsing resumes only after it is fully loaded and executed.

< script src ="myBlockingScript.js" ></ script >

During loading, the browser does not do various useful work, such as parsing HTML, executing other scripts and rendering. And despite the fact that some of the problems are taken over by the webkit preloading scanner, which theoretically should look at the page for resources that need to be loaded during idle time, delays still remain decent.

There are a lot of techniques trying to solve this problem, but all of them are hacks in their essence. Instead, we have the opportunity to mark scripts that do not require synchronous download, as async or defer . Here is how it works.
')
< script async src ="myAsyncScript.js" onload ="myInit()" ></ script >
<script defer src= "myDeferScript.js" onload= "myInit()" > </ script >


In both cases, scripts marked as async or defer immediately begin to download without causing the parser to stop, and both scripts support an onload handler that allows you to trigger certain events when the script is loaded. Each script labeled async will be executed at the moment when it will be possible after it is fully loaded, but before the window loading event is thrown. This means that such scripts are likely to be executed not in the order in which they are listed on the page. But the presence of defer scripts ensures that as they are specified, so they will be loaded. Their execution will begin after the parser completes, but before the DOMContentLoaded event appears .

Here is an example in which the load time of the external script takes 1 second, followed by the execution of the script located in the body of the page, which takes another 1 second. As a result, loading the page takes 2 seconds.



Here is the same example, but for the case when the script is marked as defer. While the second script is executed, the first one is quietly loaded, which causes the page to load 2 times faster.



In addition to the above, I would like to note that Firefox supported the defer and onload properties for a long time, and in version 3.6 support for async was added. Internet Explorer has also supported the defer parameter for a long time. The async property will still not support in any of the versions, while onload will appear in version 9 already.

Source: https://habr.com/ru/post/104795/


All Articles