Load them asynchronously. Asynchronous JavaScript loading - speed up page loading


/ 26.01.2018

With the increase in Internet connection speed and the increase in power not only of desktop, but also mobile devices Web pages are becoming heavier. The number and size of connected files is growing: JavaScript files, css files, images, third-party site widgets, iframes. On this moment The specifics of how browsers work is such that when loading a js file, rendering is blocked until the script is executed. Modern browsers V background will parse the document and download scripts and styles, but rendering will be blocked. Comparison network parameters For different browsers can be viewed at browserscope.org. We cannot eliminate blocking completely, but we can optimize the server and client parts of the application so that render blocking takes the shortest amount of time.

Server side solutions:
— Reduce size transferred files
— Use CDN
— Place static files on separate domain or under a domain, thus increasing the number of simultaneous browser connections.
— Enable compression of transferred files (gzip)

Solutions for the client side:
— Reduce the number of requests.
- Cache files on the client side using the Expires and Etags headers.
— Use publicly available CDNs (Google CDN, Yandex CDN). So there is a possibility that the file from the public CDN will already be stored in the browser cache.

One way to optimize site loading speed is asynchronous loading files that does not block rendering.

JavaScript asynchronous loading script:

(function() ( var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'File URL'; document.getElementsByTagName('head') .appendChild(script); ))();

If JavaScript needs to be executed after the entire page has loaded, including content, images, style files and external scripts, then you need to add tracking of the onload event to the loader.

if (window.addEventListener) ( window.addEventListener('load', async_load, false); ) else if (window.attachEvent) ( window.attachEvent('onload', async_load); )

JavaScript asynchronous loading script based on the onload event

(function() ( function async_load())( var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'File URL'; document.getElementsByTagName ('head').appendChild(script); ) if (window.addEventListener) ( window.addEventListener('load', async_load, false); ) else if (window.attachEvent) ( window.attachEvent('onload', async_load ); ) ))();

But this single case when a single file needs to be downloaded. Often in practice many files are connected.

Script for asynchronously loading multiple connectors JavaScript files

(function() ( function async_load())( [ 'URL_1.js', 'URL_2.js', 'URL_3.js' ].forEach(function(src) ( var s = document.createElement('script'); s .type = 'text/javascript'; s.async = true; s.src = src; document.getElementsByTagName('head').appendChild(script); )); ) if (window.addEventListener) ( window.addEventListener( 'load', async_load, false); ) else if (window.attachEvent) ( window.attachEvent('onload', async_load); ) ))();

But there is a minus in this implementation - the scripts will be loaded in random order and, accordingly, they will be executed randomly in time. This asynchronous loading script is ideal if JavaScript execution files do not depend on one another and do not depend on the DOM. Otherwise, its use may lead to errors on the page or unexpected execution results. For sequential execution, but asynchronous downloading, you need to specify async=false, then the files will be downloaded in random order, but executed in turn.

The HTML 5 standard supports asynchronous loading of JavaScript. This can be done by adding keyword async or defer. For example:

.jpg" type="text/javascript" defer>

A script that is connected with the defer attribute will be executed without disturbing the order of execution in relation to other scripts and its execution will occur after the page is fully loaded and parsed, but before DOMContentLoaded is called.

A script that is connected with the async attribute will be executed as soon as possible after it has been fully loaded, but it does not wait for the document to be parsed before loading the window object. Browsers do not guarantee that scripts will be executed in the same order in which they are connected.

Libraries for asynchronous JavaScript loading

RequireJS is a JavaScript loading module. Optimized for browsers, but it can be used in other environments such as Node, Rhino.

require(["script"], function(script) ( console.log("start after load script.js"); ));

extsrc.js is a library that runs scripts to be executed after the page is loaded and displayed to the user. Works correctly with document.write.

.jpg">.jpg">

yepnope.js - allows for asynchronous loading of JavaScript and CSS files.

yepnope([ 'script.js', 'style.css' ]);

Easy way to download JavaScript scripts

It turns out that in practice, achieving optimal cross-browser loading of JavaScript scripts that do not block display is difficult, and sometimes impossible..jpg"> at the end of the document before the closing body tag. Due to restrictions different browsers and HTML itself, such a loading option that does not block display can be considered the simplest.

Google PageSpeed: CSS styles and JavaScript scripts that block page loading on WP

This post will assume that you are familiar with Google tool for optimizing site page loading speed - PageSpeed ​​Insights. Listen, right now enter your website there and click the “Analyze” button.

Okay, now what is this post about?

It is quite possible that in the results of checking your site there is an item “Eliminate render-blocking JavaScript and CSS in above-the-fold content”.

I noticed that this point is one of the most intractable (time-consuming) and is present on almost all sites, even very fast ones.

How to fix it in theory:

  • We combine all the JavaScript files and place what we got before the closing tag of the site.
  • We combine all the CSS, put it right in front of the JavaScript that we have already moved, then select from them those styles that are necessary for the correct display of the page, and especially its top part (the first screen) and place them in a tag in the site.
  • How does this work in practice, and in this particular case - for WordPress sites?

    1. Let's take advantage of the dependence of other scripts on jQuery

    In correctly concocted WordPress theme all CSS and JS files are connected via wp_head() and wp_footer() - that is, at and at the end, respectively.

    Also, the files have dependencies, that is, for example, the plugin must be connected after, which means that if jQuery library is in wp_footer(), then FancyBox can’t get into wp_head().

    Moving jQuery to the site footer

    This is done very simply - using the functions wp_deregister_script(), wp_register_script(), wp_enqueue_script() and a hook (sometimes a hook is used in conjunction with is_admin()). All you need to do is paste the following code into your website file.

    I would like to draw your attention to the fact that this is an automated solution, and although it works in almost 100% of cases, it happens that some scripts do not want to be transferred to the site footer. Then you will need to be more attentive to each of your JavaScript files.

    This is where our work with JS ends, of course, merging scripts will also give a speed boost (that is, you unregister them all and then simply connect your combined version) - but Google no longer requires this.

    2. Combining CSS in WordPress

    If combining all JavaScript into one file is not always good idea, then I would recommend combining CSS whenever possible.

    Remember the screenshot at the very beginning of the article ( 10 blocking CSS resources)? Where do so many style files come from, since the theme developer probably knew what he was doing?

    The answer is from plugins.

    For example, the plugin Contact Form 7" includes its own style sheet, and although it is not large in itself, it is still better to avoid unnecessary HTTP requests.

    Let's look at how step by step.

  • Copy the contents of the plugin's style sheet and paste it at the end of the main style file - .
  • Check whether these styles contain relative links to images, for example. If yes, then either replace them with absolute ones, or move the images from the plugin to the theme folder.
  • Go to the plugin settings and see if there is an option to uncheck the box somewhere and not include the plugin’s CSS. There is no such option in Contact Form 7, which means we move on to the next point.
  • We chop off files via. For Contact Form 7 styles the code will be as follows:
  • Also, sometimes using conditional tags, plugin files (both CSS and JS) are disabled only from those pages where they are not used.

    Ok, we’ve sorted out Contact Form 7, but how can you find out the IDs of the CSS files of other plugins?

    It's easy, let's open it source page and we see a similar picture there:

    There is also a plugin that will allow you to combine CSS and JavaScript automatically - JS & CSS Script Optimizer.

    If you have any questions or I forgot to mention anything in this article, please leave a comment.

    How the browser loads the page

    The browser loads the page sequentially. This is especially true for external links for files - css and javascript. Let's take for example a block for the site lesnoy.name.

    Blog of Lesnoy Vladislav

    This site only loads three external files.

    2 of them - css styles, and one is a js file. But this is an example of a simple site, dozens of times are loaded external files and this significantly affects the page loading speed.

    Speed ​​up page display in the browser

    Everything would be fine, but the main problem is that the browser works as follows: when it encounters a link to an external file, it downloads and processes it, pausing rendering of the rest of the page.

    That is, from the example above it is clear that the browser will load the site title (title), then encounter a link to external css main.css file and will go to load it. After loading, it processes it and moves on - it encounters the second css file, again postpones processing the page until later and works with prettify.css. Same with prettify.js. And only then does it begin to display the rest of the page, already applying all the previously processed css rules from css files and js rules from javascript files.

    At slow internet or a large number of external files, the time between going to the page and rendering it can reach tens of seconds, or even more than a minute. But isn’t it possible, while external files are loading, to display the text from the page that the visitor actually came for?

    Of course it is possible. The most banal, but no less effective method— transfer of all non-priority external files from the site header to the footer. Those. from the head block as close to the tag as possible.

    By non-priority files I mean those that are not critical to functionality or appearance site. Good way divide big css or a js file into two - the first small one stores what should load as quickly as possible and is placed in the head section, and the second and large one contains everything else and is located as low as possible in the html code of the page, without affecting the speed of content display pages.

    But with the advent of html5 you can do it easier and more beautiful. The script tag has an async and defer parameter added.

    async attribute

    The script async attribute makes loading js files asynchronous. Those who know how to program in JS know exactly how it is - asynchronously. For those who don’t know how, I’ll tell you: the browser encounters a link to an external javascript file (script tag with the src parameter), begins loading and processing it, but does not stop loading and processing the main page.

    Those. does this in parallel. Just what we need! And at the same time, there is no need to move this tag to the footer (especially not in all CMS systems this is easy to do).

    Disadvantage of the async attribute

    For asynchronous loading of a js file, asynchrony is both a plus and a minus. After all, file sizes are most likely different, and the speed of downloading and processing files is also not deterministic. This means that when loading several files asynchronously, there is no guarantee that a file that starts loading later will not end up loading earlier (mainly due to its size).

    IN in this example I can't say exactly what the execution sequence of these js files will be. All I can say for sure is that script4 will load after script3 due to the lack of an async attribute. But I don’t know which file from script1.js, script2.js and script5.js will load first, because they are loaded asynchronously.

    Insert/edit link

    “And what difference does it make to us?” - you ask. But it appears if the execution of one js script depends on another. This happens all the time now, and the simplest example of such a dependence is jQuery.

    IN in this case there is a very high probability of receiving JavaScript errors due to the fact that any of jQuery plugins will start executing before jQuery itself loads.

    What to do?

    defer attribute

    This is where another attribute of the script tag comes to our rescue - defer.

    Deferred to be transferred from in English as "deferred".

    Respectively deferred javascript load— deferred loading javascript. If the browser encounters a defer attribute on a link to an external js file, it defers loading and executing these files until the entire page has been loaded and displayed. At the same time, it guarantees the same order of script execution, which was originally set in the html code.

    Accordingly, in our example with jQuery and its plugins, defer helps us out by performing two tasks: the page display time is significantly reduced (the browser does not block the rendering of the page for loading js files, it postpones loading until later) and at the same time we get rid of possible errors related to asynchronous loading of mutually dependent js files.

    In the example above, the other_script.js script will load asynchronously, because it does not depend on any other file, and jQuery and its plugins will be loaded immediately after the page is rendered in the following order: first jquery.min.js, then in order plugin1.jquery.js, plugin2.jquery.js, plugin3.jquery. js.

    As a result, with the advent of html5 and the defer and async attributes, we can control the loading order of external js files much more flexibly, thereby increasing the speed of web page rendering. And, most importantly, the user will get the impression of a significant increase in the loading speed of the entire website as a whole, because in just a few seconds he will see what he came to the site for - information.

    All my thoughts were aimed at solving the main problem:

    In general [when using data:URL], page loading will not speed up, and may even slow down, because background images (enabled via data:URL) will be loaded in one thread, rather than in multiple threads. normal use sprites. If there are quite a lot of background images (several tens of KB), then this will be significant.

    This article is dedicated to how you can successfully cope with this problem. Interesting? Then, let's go.

    Formulation of the problem

    When using data:URL, the resulting CSS file is quite large (in fact, the size of all images * 1.2...1.5 + base CSS). And this is in the form of an archive. If the file is not zipped, then its additional size increases many times (2.5-3 times relative to the size of all background images), but this is not so significant, because there are currently only a few users with disabled compression for CSS files.

    What do we actually need? First, you need to divide the entire array of CSS rules into those that apply to background images and those that do not. Secondly, tell browsers that they can display the page without the first rules array (after all, if it only contains background images, then they can wait a little).

    What are we achieving in this way? In fact, using this approach, we create a different container for background images (not a resource image, but a CSS file), which is more convenient to use in most cases. We combine all the background images not through CSS Sprites, but through data:URL, and we can load them all in one file (in which each image will be stored completely separately). At the same time, we avoid any problems with background positioning.

    Theoretical solution

    Everything ingenious is simple, so we can load a light-weight CSS file at the beginning of the page (without any background images, only basic styles, just to display the page correctly), then use the combined window.onload to load dynamic style files in 2-4 threads.

    Possible disadvantages: after loading each additional CSS file, the page will be redrawn. If there are only 1 or 2 such files, then the page will be displayed much faster.

    Why don't we parallelize the loading of style files at the very beginning of the document? Because two files will load slower than one. In addition, we advocate for the page to be displayed as quickly as possible in the user's browser, so the initial amount of CSS loaded should be minimal (you can also consider options for including it in the HTML itself).

    On practice

    In practice, everything turned out to be not much more complicated. We load in the head of the page (before calling any external files) our “lightweight” CSS:

    And then we add to the combined window.onload (at the very beginning) the creation of a new style file, which complements the one already loaded with background images:

    Function combinedWindowOnload() ( load_dynamic_css("background-images.css"); ... )

    As a result, we have the fastest possible display of the page, and then the post-loading stage, which will pull everything from the server additional pictures(here the browser itself will try), style rules and scripts.

    What about accessibility?

    Attentive readers have already prepared a question: what if the user has JS disabled? Well, it should be simple: we add the appropriate noscript to support such users.

    With a small nuance: noscript cannot be in head, and link cannot be in body. If we comply with the standards (still, sometimes it is better to trust the professionals and not put browsers in an awkward position when they encounter another deviation from the specification), then it is worth looking for workarounds.

    After a little experimentation with the styleSheets collection and other DOM objects, the following elegant solution was identified that ensures that the schema works in all browsers (note: after a lot of experimentation, it was decided to stick with HTML comments: they turned out to be in the best possible way prevent loading of the specified CSS file):

    /* if we can create a dynamic stylesheet */ if (document.getElementsByTagName) ( /* then add a lightweight version to the download */ document.write("\x3clink href="light-light.css" rel="stylesheet" type ="text/css" media="all"/>"); /* after this we start the HTML comment */ document.write("\x3c--"); )

    As a result, the browser with JavaScript enabled will record the beginning of the comment and close it only after (comments cannot be nested). When disabled, JavaScript will not run; it will be processed and added to the download queue, and the last comment will be just a comment.

    Why are comments also conditional comments for IE? Just because Firefox reacted strangely to ordinary empty comments, and I'm now looking for a cross-browser solution.

    Rake, rake, rake...

    During testing in Internet Explorer It was discovered that if you add a style file immediately in parallel with the scripts (in a function that is triggered for it by onreadystatechange), then IE “freezes” the initial rendering of the page (i.e. shows White screen) until it receives a “fresh” style file. I had to insert a dummy delay for it like this:

    SetTimeout("load_dynamic_css("background-images.css")",0);

    In Safari, the logic of displaying a page depending on the downloaded files is different from all browsers. You can read more in this article about the FOUC problem and possible solutions. In a nutshell, you can strictly define the initial set of files needed to display the page on the screen (HTML/CSS/JS), or you can start loading all the files in order of priority (and fulfilling all their dependencies) and check from time to time, you can whether to already display the page (performing all calculations in the background without refreshing the screen). In general, Safari has the second approach, so nothing beats loading the dynamic CSS file from background pictures after firing window.onload (which, in fact, fires earlier than in all other browsers) I couldn’t come up with. But the original image appears faster in the browser.

    So, if you take the combined window.onload at once and add loading styles to it, you will get something like this:

    /* declare a function for dynamically loading styles and scripts, the first parameter is the path to the file, the second is the file type Unfortunately, the function is declared global */ function loadDynamic (src,type)( var node=document.createElement(type?"link": "script"); node = document.getElementsByTagName("head").appendChild(node); /* if we pass the second parameter, then this is a stylesheet */ if(type)( node.setAttribute("rel","stylesheet" ); node.setAttribute("media","all") ) node.setAttribute("type","text/"+(type?"css":"javascript")); node.setAttribute(type?"href" :"src",src) ) (function())( /* slightly modified version of the handler */ function combinedWindowOnload())( if(arguments.callee.done)(return) arguments.callee.done=true; if(document.getElementsByTagName )( /* if not Safari, then load the CSS with background images dynamically */ if(!/WebKit/i.test(navigator.userAgent))( /* add a pseudo-delay to bypass IE */ setTimeout("loadDynamic(" background-images.css",1)",0); ) /* set the flow to load all our scripts */ loadDynamic("some_scripts.js"); ) ) /* then comes the standard cross-browser code with */ ... /* we attach a handler for the Onload event to the window, thanks to lusever for the compact form */ window(/*@cc_on "on"+@*/"load",function ()( /* if Safari, then finally load this CSS */ if(/WebKit/i.test(navigator.userAgent))( loadDynamic("background-images.css",1); ) /* additional call to WindowOnload for "old" browsers */ combinedWindowOnload() ),false) ))()

    Winning

    If you have large quantity small decorative background images (for example, each page uses from 30 to 40 different pictures, the total volume of which is about 30Kb), which can also be repeated in different directions, it can be very convenient to combine them all into one file that can be uploaded after the page is displayed on the screen.

    The described technique (cross-browser data:URL + dynamic loading of style files) allows you to achieve all the advantages of CSS Sprites technology without delaying page loading. At the same time, it has obvious advantages: you don’t need to put all the pictures into one file, you can work with each one completely separately, which allows you to achieve greater semantics of the code and greater ease of use of sites. In addition, this will reduce the CSS code somewhat by eliminating the need to use background-position .

    Despite the increasing spread of broadband Internet access, problems with the speed of loading HTML pages are still not indifferent to many Internet users, especially in the vastness of the former Soviet Union. CSS (Cascading Style Sheets) can help in this matter, saving us time and traffic.

    1. Avoid using tables for page layout

    Here are six reasons why it's better to use CSS rather than tables for page layout:

    • Browsers parse tables twice: once to evaluate the table's structure, and once to determine its contents.
    • Tables are displayed in full immediately, and not as they load.
    • Tables are forced to use transparent pictures to determine the width of columns, etc.
    • CSS requires much less code than overloaded tables.
    • All CSS code can be exported to an external file, which will be loaded only once and stored in the browser cache.
    • At CSS help You can control the order in which page elements are loaded.
    2. Don't use pictures to display text

    Most buttons and labels can be rendered using CSS. Take a look at the example:

    a:link.example, a:visited.example, a:active.example ( color:#fff; background:#f90; font-size:1.2em; font-weight:bold; text-decoration:none; padding:0.2 em; border:4px #00f outset ) a:hover.example ( color:#fff; background:#fa1; font-size:1.2em; font-weight:bold; text-decoration:none; padding:0.2em; border :4px #00f inset

    This CSS defines simple button, which changes its appearance when you hover the cursor. This way you can create more complex objects.

    3. Loading images via CSS

    Some background images are better loaded via CSS. For example, to display a 200x100 image, you can use the following code:

    And the corresponding CSS:

    Pretty-image ( background: url(filename.gif); width: 200px; height: 100px )

    This may seem pointless at first, but it can actually make your page load much faster. In this case, the browser will start loading the image only after all the text has been displayed, and not simultaneously. This way, users can work with the page while the image is still loading.

    This technique is best suited for loading purely decorative, background page elements. If the image is part of the content, you will still need to use the IMG tag.

    4. Using contextual styles

    This code is ineffective:

    This is a sentence

    This is another sentence

    This is yet another sentence

    This is one more sentence

    .text ( color: #03c; font-size:2em )

    Instead of assigning a class to each paragraph, they can be grouped into one DIV element with the same class:

    This is a sentence

    This is another sentence

    This is yet another sentence

    This is one more sentence

    .text p ( color: #03c; font-size:2em )

    This code tells the browser that each paragraph inside an element with class text will have a color of #03c and a font size of 2em.

    You may have noticed that the color here is indicated in only three characters, not six. In this case, #03c is a shorthand for the color value #0033cc.

    5. Using abbreviations

    Font

    It's better to write:

    font: 1em/1.5em bold italic serif

    font-size: 1em; line-height: 1.5em; font-weight: bold; font-style: italic; font-family: serif

    Borders

    border: 1px black solid

    border-width: 1px; border-color: black; border-style: solid

    Background

    background: #fff url(image.gif) no-repeat top left

    background-color: #fff; background-image: url(image.gif); background-repeat: no-repeat; background-position: top left;

    Padding and Borders

    Use:

    margin: 2px 1px 3px 4px; (top, right, bottom, left)

    Likewise:

    margin: 5em 1em 3em; (top, left and right, bottom)

    margin: 5% 1%; (up and down, left and right)

    These rules apply to the margin, border, and padding attributes.

    6. Minimize spaces, line breaks and comments

    Each character - letter or space - takes up one byte. Each extra character only increases the size of the pages. Therefore, try to press Enter and Tab less during the layout process. Also, don't forget to combine CSS styles.

    7. Use relative links

    Absolute links take up much more space than relative ones. And besides, it creates additional load on the browser, which is more important. An example of an absolute link: . It would be much more correct to write< a href=»filename.htm»>. But what if the file you need is in a different directory? Here are some examples to help you understand this issue:

    8. Don't get carried away with using META tags

    Most META tags are completely unnecessary. If you're interested, you can take a look at all the existing options. The most important tags (keywords and description) are used for search engine optimization. When using the content attribute in the META tag, try to keep it under 200 characters. Large descriptions and many keywords can be perceived as spam by search engines.

    9. Keep CSS and JavaScript in separate files

    Everyone knows this, but they don’t always use it. This is what a CSS call from an external file looks like:

    And accordingly JavaScript:

    Any external file is downloaded only once and then stored in the local cache. There are no restrictions on the number of “connected” external files.

    10. Place / (slash) at the end of directory links

    It needs to be written like this.

    There is a way out: place the Javascript lines at the end of the html document (therefore, they will be loaded after the entire page is drawn) and only after that the contents of the blocks will be displayed in the right places. It is called . All serious projects today are trying to switch to new loading technology as quickly as possible. Moreover, it is absolutely easy.

    There are several approaches. I'll start in order.

    script src= type= "text/javascript" >

    Asynchronous loading of HTML5 script

    The HTML5 standard supports the ability to load scripts asynchronously, which can significantly speed up the overall page retrieval time. Just add async or defer .

    < script async src= "http://www.site.ru/script.js" type= "text/javascript" >

    < script defer src= "http://www.site.ru/script.js" type= "text/javascript" >

    What is the difference between the async and defer attributes?

    In both cases we get asynchronous loading of scripts. The only difference is the moment when the script starts executing. A script with the async attribute will be executed as soon as possible after it is fully loaded, but before the window object is loaded. If the defer attribute is used, the script will not violate the order of its execution in relation to other scripts and its execution will occur after the page is fully loaded and parsed, but before the DOMContentLoaded event of the document object.

    Unfortunately, this mechanism does not currently work in all browsers (especially IE). Also won't work if there are document.write lines in the script.js file.

    Asynchronous javascript loading with Google script

    As all experts know, Google pays special attention to the loading speed of sites and lowers slow ones in search results. To help, Google has developed a special script with which you can make asynchronous javascript loading.

    To use, simply replace

    on

    And connect the script file extsrc.js

    It will turn out like this:

    < script src= "http://extsrcjs.googlecode.com/svn/trunk/extsrc.js" > < script extsrc= "...." >

    Unfortunately, this method also does not work for files with document.write

    Best working asynchronous javascript loading

    A universal method for all browsers. Even works with document.write

    In the place on the page where we need to actually display our element, create an empty div block:

    < div id= "script_block" class = "script_block" >

    At the very end of the page, before we insert a script for asynchronously loading files:

    < div id= "script_ad" class = "script_ad" style= "display:none;" >Here is any file or script that needs to be loaded.< script type= "text/javascript" >// move it to the actual display position document. getElementById("script_block" ) . appendChild(document. getElementById("script_ad" ) ) ; // show document. getElementById("script_ad" ) . style. display = "block" ;

    In the oldest versions of IE (6 and below), asynchronous loading unfortunately does not work, but there are practically no such users anymore. All other browsers and services successfully use modern accelerated loading of web pages.

    With the increase in Internet connection speed and the increase in power of not only desktop, but also mobile devices, web pages become more “heavy”. The number and size of connected files is growing: JavaScript files, css files, images, third-party site widgets, iframes. At the moment, the specifics of browsers are such that when loading a js file, rendering is blocked until the script is executed. Modern browsers will parse the document in the background and download scripts and styles, but rendering will be blocked. A comparison of network settings for different browsers can be found at browserscope.org. We cannot eliminate blocking completely, but we can optimize the server and client parts of the application so that render blocking takes the shortest amount of time.

    Server side solutions:
    - Reduce the size of transferred files
    - Use CDN
    - Move static files to a separate domain or subdomain, thus increasing the number of simultaneous browser connections.
    - Enable compression of transferred files (gzip)

    Solutions for the client side:
    - Reduce the number of requests.
    - Cache files on the client side using the Expires and Etags headers.
    - Use publicly available CDNs (Google CDN, Yandex CDN). So there is a possibility that the file from the public CDN will already be stored in the browser cache.

    One way to optimize site loading speed is to load files asynchronously, which does not block rendering.

    JavaScript asynchronous loading script:

    (function() ( var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.src = "File URL"; document.getElementsByTagName("head") .appendChild(script); ))();

    If JavaScript needs to be executed after the entire page has loaded, including content, images, style files, and external scripts, then the onload event needs to be added to the loader.

    If (window.addEventListener) ( window.addEventListener("load", async_load, false); ) else if (window.attachEvent) ( window.attachEvent("onload", async_load); )

    JavaScript asynchronous loading script taking into account the onload event (function() ( function async_load())( var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.src = "File URL"; document.getElementsByTagName("head").appendChild(script); ) if (window.addEventListener) ( window.addEventListener("load", async_load, false); ) else if (window.attachEvent) ( window .attachEvent("onload", async_load); ) ))();

    But this is an isolated case when downloading a single file is required. Often in practice many files are connected.

    Script for asynchronously loading multiple plug-in JavaScript files (function() ( function async_load())( [ "URL_file_1.js", "URL_file_2.js", "URL_file_3.js" ].forEach(function(src) ( var s = document.createElement ("script"); s.type = "text/javascript"; s.async = true; s.src = src; document.getElementsByTagName("head").appendChild(script); )); ) if (window. addEventListener) ( window.addEventListener("load", async_load, false); ) else if (window.attachEvent) ( window.attachEvent("onload", async_load); ) ))();

    But there is a minus in this implementation - the scripts will be loaded in random order and, accordingly, they will be executed randomly in time. This asynchronous loading script is ideal if the execution of JavaScript files does not depend on one another and does not depend on the DOM. Otherwise, its use may lead to errors on the page or unexpected execution results. For sequential execution, but asynchronous downloading, you need to specify async=false, then the files will be downloaded in random order, but executed in turn.

    HTML 5. Asynchronous JavaScript Loading

    The HTML 5 standard supports asynchronous loading of JavaScript. This can be done by adding the async or defer keyword. For example:

    A script that is connected with the defer attribute will be executed without disturbing the order of execution in relation to other scripts and its execution will occur after the page is fully loaded and parsed, but before DOMContentLoaded is called.

    A script that is connected with the async attribute will be executed as soon as possible after it has been fully loaded, but it does not wait for the document to be parsed before loading the window object. Browsers do not guarantee that scripts will be executed in the same order in which they are connected.

    Libraries for asynchronous JavaScript loading

    RequireJS is a JavaScript loading module. Optimized for browsers, but it can be used in other environments such as Node, Rhino.

    Require(["script"], function(script) ( console.log("start after load script.js"); ));

    extsrc.js is a library that runs scripts to be executed after the page is loaded and displayed to the user. Works correctly with document.write.

    yepnope.js - allows for asynchronous loading of JavaScript and CSS files.

    Yepnope([ "script.js", "style.css" ]);

    An easy way to load JavaScript scripts

    It turns out that in practice, achieving optimal cross-browser loading of JavaScript scripts that do not block display is difficult, and sometimes impossible. Most optimal way is added to the end of the document before the closing body tag. Due to the limitations of different browsers and HTML itself, this download option, which does not block display, can be considered the simplest.





    

    2024 gtavrl.ru.