Home  >  Article  >  Web Front-end  >  Lazy loading JavaScript

Lazy loading JavaScript

大家讲道理
大家讲道理Original
2017-01-24 16:03:351667browse

How to Lazy Load JavaScript

True lazy loading of JavaScript means: loading or parsing JavaScript only after the page content has been fully loaded (this means that JavaScript cannot affect page speed or criticality) rendering path).

  • Use the "onload" event to call external JavaScript resources

  • External JavaScript resources cannot be loaded before the page content is loaded

  • External JavaScript resources do not start running until the content is loaded and affect the page

Explanation

The focus on the Internet is often people trying to find a Crazy about various solutions, JavaScript lazy loading is one of the focuses.

Many people say "just use defer", "just use async", or "just put your JavaScript at the bottom of the page", but these are not solved Problem - Let the page fully load and then (only after fully loading) load the external JS. These methods will also not let you pass the "delayed loading JavaScript" warning obtained from the Google Page Speed ​​Tool (the translator has some doubts about this, because during testing I found that the above three methods can remove this warning).

This solution will answer.

Script that calls an external JavaScript file

This code is placed before the 36cc49f0c466276486e50c850b7e4956 tag of the HTML document (near the bottom of the HTML document). The name of the external script is defer.js.

<script type="text/javascript">function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js";
    document.body.appendChild( element );}if ( window.addEventListener ) {
    window.addEventListener( "load", downloadJSAtOnload, false );} else if ( window.attachEvent ) {
    window.attachEvent( "onload", downloadJSAtOnload );} else { 
    window.onload = downloadJSAtOnload;}
</script>

What does this script do?

This code says to wait until the document is completely loaded, and then load the external file "defer.js".

Details

  • 1. Copy the above code

  • 2. Paste the code into your HTML document, 36cc49f0c466276486e50c850b7e4956Before the tag

  • 3. Change defer.js to the name of your external file

  • 4. Make sure the path to your file is correct. For example: If you use "defer.js", then the "defer.js" file must be in the same folder as your HTML file

What can you use it for (or What can’t be done)

This code will not load external link files until your page is completely loaded. You should split your JavaScript into two groups, one that the page needs to load, and another that does what it needs to do after the page loads (such as looking for click events or other things). Any JavaScript that is acceptable to wait and wait until the page loads should be called from an external file.

For example, in this page I used the above script to delay loading Google statistics, Viglink, and the Google plus avatar at the bottom. I have no reason to load these files at the beginning of the page, because these files are not related to the content I mentioned above and are not required to be loaded. Maybe you would have the same type of thing on your page, would you make the user wait for those resources to load before showing them your user content?

Why can’t other methods work?

Inline, put the script at the bottom, use defer or async These methods are not completed first let the page load, then load the JS target, and These methods are indeed not universal and cross-browser.

Why is this important?

This is because Google uses page loading speed as a ranking factor, and because users want pages to load faster. This will also be of great benefit to your mobile SEO. Google measures your page loading speed from the time it is called until the initial load of the page is completed. This also means that you need to make the page's load event complete as quickly as possible. Google evaluates your page based on its homepage load time (and don’t forget, users are waiting for the page to load).

Google’s active promotion and recommendationprioritizing above the fold content (screen content takes priority). So keeping any off-screen resources (js, css, images, etc.) out of the main rendering path is worth the effort. If it makes your users happy and Google happy, why not do it.

Usage Example

I created a page, click here, you will see that I used the above code snippet.

Testing sample files

Okay, to illustrate, I wrote some test pages for you to test. Each page does the same thing. A pure HTML page uses a script. The content of the script is to wait for two seconds to output "hello world". You can test these pages and see that there is only one way to display the content immediately (the page load time does not include the two seconds of waiting).

Key point

The most critical point is to present the content to the user as quickly as possible. We have not been doing that with how we have treated our javascript. Users have to see their content because some scripts do things underneath the visual content. No matter how cool your page bottom is, if the user never scrolls to the bottom of the page, then there is no reason for you to load the script to make the bottom of the page cool.

Tool

Use the javascript usage tool to test how JavaScript is used on your pages.


Supplementary extension

1. defer and async

Both attributes can be used for page optimization, but what is the difference? One picture can answer:

2. Below the Fold

According to the definition in wordstream:

Below the fold Refers to the area of ​​a web page that is only visible by scrolling.

Above the Fold refers to the content area that is visible without scrolling the page.

Generally speaking, content that is displayed on the screen without scrolling will receive more attention, and content that requires scrolling to be visible will receive less attention. foldViews come from the news and publishing industry.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn