Home Web Front-end JS Tutorial How to implement javascript delayed loading

How to implement javascript delayed loading

Jul 22, 2021 am 11:54 AM
js Lazy loading

Implementation method: 1. Use the setTimeout method, the syntax is "setTimeout('js method', delay time);"; 2. When introducing an external js script file, put it in the body, and it will follow the page from above Fall down the load order to run JavaScript code.

How to implement javascript delayed loading

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Lazy loading of js helps to improve the loading speed of the page. The following are several methods of lazy loading:

1. Use setTimeout to delay the loading time of the method

Delay loading of js code to allow more time for web page loading

<script type="text/javascript" >
  function A(){
    $.post("/lord/login",{name:username,pwd:password},function(){
      alert("Hello");
    });
  }
  $(function (){
    setTimeout(&#39;A()&#39;, 1000); //延迟1秒
  })
</script>
Copy after login

2. Let js be loaded last

For example, when introducing external js script files , if placed in the head of the html, the js script will be loaded into the page before the page is loaded, and if placed in the body, the JavaScript code will be run in the order in which the page is loaded from top to bottom~~~ So we You can put the files imported from outside the js to the bottom of the page, so that the js can be introduced last, thereby speeding up the page loading.

The above method 2 will also occasionally cause you to receive "delayed loading javascript" from the Google page speed test tool. warn. So the solution here will be the recommended solution from the Google help page.

//这些代码应被放置在</body>标签前(接近HTML文件底部)
<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>
Copy after login

This code means to wait until the entire document is loaded before loading the external file "defer.js".

Steps to use this code:

1). Copy the above code

2). Paste the code before the HTML tag (near the bottom of the HTML file)

3). Modify "defer.js" to the name of your external JS file

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

Note: This code will not load the specified external js file until the document is loaded. Therefore, JavaScript code that depends on normal page loading should not be placed here. Instead, JavaScript code should be separated into two groups. One group is the javascript code that is loaded immediately because the page needs it, and the other group is the javascript code that operates after the page is loaded (such as adding a click event or other things). The JavaScript code that needs to wait until the page is loaded before executing should be placed in an external file and then imported.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to implement javascript delayed loading. 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)

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

What is the architecture and working principle of Spring Data JPA? What is the architecture and working principle of Spring Data JPA? Apr 17, 2024 pm 02:48 PM

SpringDataJPA is based on the JPA architecture and interacts with the database through mapping, ORM and transaction management. Its repository provides CRUD operations, and derived queries simplify database access. Additionally, it uses lazy loading to only retrieve data when necessary, thus improving performance.

What is the original meaning of dynamic linking and static linking in Linux? What is the original meaning of dynamic linking and static linking in Linux? Feb 05, 2024 pm 05:45 PM

As usual, let’s ask a few questions: Why dynamic linking? How to do dynamic linking? What is address-independent code technology? What is delayed binding technology? How to do explicit linking while the program is running? Why dynamic linking? The emergence of dynamic linking is to solve some shortcomings of static linking: saving memory and disk space: As shown in the figure below, Program1 and Program2 contain two modules, Program1.o and Program2.o respectively, and they both require the Lib.o module. In the case of static linking, both target files use the Lib.o module, so they have copies in the executable files Program1 and program2 output by the link and run at the same time.

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Mar 06, 2024 pm 02:33 PM

Decoding Laravel performance bottlenecks: Optimization techniques fully revealed! Laravel, as a popular PHP framework, provides developers with rich functions and a convenient development experience. However, as the size of the project increases and the number of visits increases, we may face the challenge of performance bottlenecks. This article will delve into Laravel performance optimization techniques to help developers discover and solve potential performance problems. 1. Database query optimization using Eloquent delayed loading When using Eloquent to query the database, avoid

What to do if the html image is too large What to do if the html image is too large Apr 05, 2024 pm 12:24 PM

Here are some ways to optimize HTML images that are too large: Optimize image file size: Use a compression tool or image editing software. Use media queries: Dynamically resize images based on device. Implement lazy loading: only load the image when it enters the visible area. Use a CDN: Distribute images to multiple servers. Use image placeholder: Display a placeholder image while the image is loading. Use thumbnails: Displays a smaller version of the image and loads the full-size image on click.

Java JPA performance optimization tips: make your application fly Java JPA performance optimization tips: make your application fly Feb 19, 2024 pm 09:03 PM

Article keywords: JavaJPA performance optimization ORM entity management JavaJPA (JavaPersistance API) is an object-relational mapping (ORM) framework that allows you to use Java objects to operate data in the database. JPA provides a unified API for interacting with databases, allowing you to use the same code to access different databases. In addition, JPA also supports features such as lazy loading, caching, and dirty data detection, which can improve application performance. However, if used incorrectly, JPA performance can become a bottleneck for your application. The following are some common performance problems: N+1 query problem: When you use JPQL queries in your application, you may encounter N+1 query problems. In this kind of

How does Hibernate optimize database query performance? How does Hibernate optimize database query performance? Apr 17, 2024 pm 03:00 PM

Tips for optimizing Hibernate query performance include: using lazy loading to defer loading of collections and associated objects; using batch processing to combine update, delete, or insert operations; using second-level cache to store frequently queried objects in memory; using HQL outer connections , retrieve entities and their related entities; optimize query parameters to avoid SELECTN+1 query mode; use cursors to retrieve massive data in blocks; use indexes to improve the performance of specific queries.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles