Home Web Front-end JS Tutorial Issues related to file loading optimization in js

Issues related to file loading optimization in js

Jun 13, 2018 pm 06:16 PM
js optimization load document

Below I will share with you an article based on js file loading optimization (detailed explanation), which has a good reference value and I hope it will be helpful to everyone.

In the js engine part, we can understand that when the rendering engine parses the script tag, it will give control to the JS engine. If the script loads an external resource, it needs to wait until it is downloaded before it can be executed. So, here, we can do a lot of optimization work on it.

Place it at the bottom of the BODY

In order to allow the rendering engine to render the DOM tree as early as possible, we need to place the script at the bottom of the body so that the page can be detached as soon as possible The white screen phenomenon means that the DOMContentLoaded event will be triggered early. However, even if you put the js script at the end of the body in IOS Safari, Android browser and IOS webview, the result will still be the same. So additional operations are needed here to optimize js file loading.

DEFER loading

This is a script attribute defined in HTML4, which is used to represent , when the rendering engine encounters a script, if the script refers to an external resource, it will temporarily suspend and load. The rendering engine continues to parse the following HTML document. When the parsing is completed, the script in the script will be executed.

<script src="outside.js" defer></script>
Copy after login

His support is <=IE9.

And its execution order is strictly dependent, that is:

<script src="outside1.js" defer></script>
<script src="outside2.js" defer></script>
Copy after login

When the page is parsed , he will start executing the outside1 and outside2 files in sequence.

If you use defer below IE9, you may encounter that the two of them are not executed sequentially. Here you need a hack to handle it, that is, add an empty script tag between the two

<script src="outside1.js" defer></script>
<script></script> //hack
<script src="outside2.js" defer></script>
Copy after login

ASYNC loading

async is a newly defined script attribute in H5. It is another js loading mode.

The rendering engine parses the file. If it encounters script (with async)

continues to parse the remaining files and loads the external resources of the script in parallel.

When the script is loaded , the browser stops parsing the document, gives permission to the JS engine, and specifies the script to be loaded.

After execution, resume the browser parsing script

It can be seen that async can also solve the problem of blocking loading. However, async is executed asynchronously, causing the order of executing files to be inconsistent. That is:

<script src="outside1.js" async></script>
<script src="outside2.js" async></script>
Copy after login

At this time, whoever finishes loading first will be executed first. Therefore, generally dependent files should not use async but should use defer.

defer has poor compatibility and is IE9, but it is generally used on mobile terminals, so this problem does not exist.

Script asynchronous

Script asynchronous is the basic loading principle used by some asynchronous loading libraries (such as require). Directly enter the code:

function asyncAdd(src){
  var script = document.createElement(&#39;script&#39;);
  script.src = src;
  document.head.appendChild(script);
}
//加载js文件
asyncAdd("test.js");
Copy after login

At this time , files can be loaded asynchronously without blocking effects.

However, the js files loaded in this way are out of order and dependent files cannot be loaded normally.

At this time, we need to optimize the above function.

var asyncAdd = (function(){
  var head = document.head,
    script;
  return function(src){
    script = document.createElement(&#39;script&#39;);
    script.src= src;
    script.async=false;
    document.head.appendChild(script);
  }
})();
//加载文件
asyncAdd("first.js");
asyncAdd("second.js");
//或者简便一点
["first.js","second.js"].forEach((src)=>{async(src);});
Copy after login

However, if you use a script to load in one step, you need to wait for the css file to be loaded before starting to load, which cannot make full use of the browser. Advantages of concurrent loading. This problem does not occur when using static text to load async or defer.

When using scripts to load asynchronously, you can only wait for the css to be loaded before loading.

When using static async loading, css and js will be loaded concurrently.

About this How to choose between the three depends mainly on what goal the leader gives us, whether it is compatible with IE8, 9, mobile phone, desktop browser, or a combination of two.

But for the scenario of using a certain skill alone, you need to pay attention to some tips when using it.

The js file should be placed at the end of the body

If you use async, add defer at the end for backward compatibility

<script src="test.js" async defer></script> //如果两者都支持,async会默认覆盖掉defer
//如果只支持一个,则执行对应的即可
Copy after login

Usually, The loads we use are all defer loads (because of strong dependencies).

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Using Async and Await functions in Node.js

##Solution to the problem that webpack cannot access 127.0.0.1

Implement remote access configuration method in webpack-dev-server

The above is the detailed content of Issues related to file loading optimization in js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box &quot;Error 0x80004005: Unspecified Error&quot; will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Detailed explanation of the role of .ibd files in MySQL and related precautions Detailed explanation of the role of .ibd files in MySQL and related precautions Mar 15, 2024 am 08:00 AM

Detailed explanation of the role of .ibd files in MySQL and related precautions MySQL is a popular relational database management system, and the data in the database is stored in different files. Among them, the .ibd file is a data file in the InnoDB storage engine, used to store data and indexes in tables. This article will provide a detailed analysis of the role of the .ibd file in MySQL and provide relevant code examples to help readers better understand. 1. The role of .ibd files: storing data: .ibd files are InnoDB storage

Create and run Linux ".a" files Create and run Linux ".a" files Mar 20, 2024 pm 04:46 PM

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension &quot;.a&quot; have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run &quot;.a&quot; files. This article will introduce how to comprehensively install and configure the Linux &quot;.a&quot; file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux &quot;.a&quot; file. What is L

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Full analysis of Go language file renaming operation Full analysis of Go language file renaming operation Apr 08, 2024 pm 03:30 PM

The os.Rename function is used in Go language to rename files. The syntax is: funcRename(oldpath,newpathstring)error. This function renames the file specified by oldpath to the file specified by newpath. Examples include simple renaming, moving files to different directories, and ignoring error handling. The Rename function performs an atomic operation and may only update directory entries when the two files are in the same directory. Renames may fail across volumes or while a file is in use.

See all articles