📜 ⬆️ ⬇️

Optimize javascript to speed up web page loading

An engineer from Google, the author of three books on web performance and optimization, Steve Souders (Steve Souders) published a presentation of "JavaScript Performance" about what methods should be used to scripts less slowed down loading pages.

According to WebPagetest statistics, blocking the download of .js files on sites from Alexa Top 100 reduces the median page load time from 3.65 seconds to 2.487 seconds , that is, by 31%. If you see slow loading of web pages and want to improve this indicator, then, according to Steve Soders, the first thing you need to look at JavaScript.

As an example of optimization, Steve Soders provides a snippet of Google Analytics .

var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); 

He pays special attention to the line
')
 ga.async = true; 

This parameter means that the ga.js script will not block the execution of other asynchronous scripts.

Another point is the insertBefore instruction. It turns out that some browsers block the execution of scripts if the script with the insertBefore instruction has not yet been loaded. Naturally, this slows down the loading of the page. In other words, such browsers will wait until the Google Analytics module is loaded on the page, and until this point all other scripts are blocked. The parameter ga.async = true corrects the situation in many modern browsers. But not all.

Steve Soders made a special page to identify those browser versions that ignore the ga.async = true instruction in the presence of insertBefore . He collected statistics from 60+ different browsers - as seen in the table by reference, the main “offender” is the Opera browser. You can run the test and check here .

In the "JavaScript Performance " presentation , Steve Soders talks about a module to speed up the loading of ControlJS scripts, as well as the use of localStorage as a cache.

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


All Articles