search
HomeWeb Front-endJS Tutorialjs performance optimization How to load your JavaScript pages faster

Make sure the code is as concise as possible

Don’t rely on JavaScript for everything. Don't write repetitive scripts. Think of JavaScript as a candy tool, just for beautification. Don't add a lot of JavaScript code to your website. Only use it when necessary. Only use it if it can really improve the user experience.

Minimize DOM access

Using JavaScript to access DOM elements is easy and the code is easier to read, but it is very slow. Here are a few key points: Limit the use of JavaScript to modify web page layout, and cache references to accessed elements. Sometimes, when your site relies on extensive DOM modifications, you should consider limiting your markup. This is a good reason to switch to HTML5 and abandon the old XHTML and HTML4. You can check the number of DOM elements by typing document.getElementsByTagName('*').length in the Firebug plug-in's console.

Compression code

To provide compressed JavaScript pages, the most effective way is to first use a JavaScript compression tool to compress your code. This compression tool can compress variable and parameter names. The resulting code is then provided, using gzip compression.

Yes, I did not compress my main.js, but you should check if there are any jQuery plugins that are uncompressed and don’t forget to compress them. Below I've listed a few options for compression.

 ◆ YUI compression tool (used by the jQuery development team), Beginner’s Guide

(http://www.slideshare.net/nzakas/extreme-JavaScript-compression-with-yui -compressor), the second guide (http://vilimpoc.org/research/js-speedup/) and the official website (http://developer.yahoo.com/yui/compressor/).

 ◆ Dean Edwards Packer(http://dean.edwards.name/packer/)

 ◆ JSMin(http://crockford.com/JavaScript/jsmin)

GZip compression: The idea behind it is to shorten the time it takes to transfer data between the browser and the server. After shortening the time, you get a file with the title Accept-Encoding: gzip,deflate. However, this compression method has some disadvantages. It takes up processor resources on both the server and client sides (for compression and decompression), as well as disk space.

Avoid eval(): Although sometimes eval() can bring some efficiency in terms of time, using it is definitely the wrong approach. eval() makes your code look dirty and will escape compression by most compression tools.

Tools to speed up JavaScript loading: Lab.js

There are many great tools to speed up JavaScript loading. One tool worth mentioning is Lab.js.

With LAB.js (Loading and Blocking JavaScript), you can load JavaScript files in parallel, speeding up the overall loading process. In addition, you can set a certain order for the scripts that need to be loaded, which ensures the integrity of dependencies. Additionally, the developer claims a 2x speed increase on its website.

Use an appropriate CDN

Many web pages now use a content delivery network (CDN). It improves your caching mechanism because everyone can use it. It also saves you some bandwidth. You can easily ping or use Firebug to debug those servers to figure out where you can speed up the data. When choosing a CDN, take into account the location of those visitors to your website. Remember to use public repositories whenever possible.

Several CDN solutions for jQuery:

◆ http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js——Google Ajax , see http://code.google.com/apis/libraries/devguide.html#Libraries for information on more libraries.

 ◆ http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js——Microsoft’s CDN

 •http://code.jquery. com/jquery-1.4.2.min.js - Edgecast (mt).

Loading JavaScript at the end of the page

If you are concerned about users and the users did not leave your page due to a slow Internet connection, this is a very good practice. Ease of use and users come first, JavaScript comes last. This may be painful, but you should be prepared for the fact that some users disable JavaScript. You can put some JavaScript in the header that needs to be loaded, but only if it is loaded asynchronously.

Loading tracking code asynchronously

This is very important. Most of us use Google Analytics to get statistics. This is good. Now take a look at where you put your tracking code. Is it in the header? Or is it using document.write? Then, if you're not using Google Analytics to track your code asynchronously, you only have yourself to blame.

This is what the Google Analytics asynchronous tracking code looks like. We have to admit, it uses DOM instead of using document.write, which may suit you better. It can detect some of these events before the web page loads, which is very important. Now think about this situation, your page hasn't even loaded and all users have closed the page. Found a solution to missing page views

var _gaq = _gaq || []; 
_gaq.push(['_setAccount', 'UA-XXXXXXX-XX']); 
_gaq.push(['_trackPageview']); 
(function() { 
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); 
})();

Not using Google Analytics? That’s not a problem, most of today’s analytics providers allow you to use asynchronous tracking.


Ajax Optimization

Ajax requests have a significant impact on the performance of your website. Below I introduce several key points about Ajax optimization.

Cache your ajax

Take a look at your code first. Is your ajax cacheable? Yes, it relies on data, but most of your ajax requests should be cacheable. In jQuery, your requests are cached by default, excluding script and jsonp data types.

Use GET for Ajax requests

POST type requests need to send two TCP packets (first send the header, then send the data). GET type requests only need to send one packet (this may depend on the number of cookies you have). So, when your URL is less than 2K in length and you want to request some data, you might as well use GET.

Using ySlow

When it comes to performance, ySlow is both simple and extremely effective. It scores your website, showing which areas need correction and which areas should be focused on.

Another trick: package your JavaScript into a PNG file

Imagine: add your JS and CSS to the end of the image, and then use CSS to crop it, through an HTTP Request to get all the information you need in the application.

I recently found this method. It basically packs your JavaScript/css data into a PNG file. After that, you can unpack it and just use the canvas API's getImageData(). Plus, it's very efficient. You can compress about 35% more without shrinking the data. And it's lossless compression! I have to point out that for larger scripts, you will feel that there is a "some" loading time while the image is pointed to the canvas and the pixels are read.

For more js performance optimization, please pay attention to the PHP Chinese website for related articles on how to load your JavaScript pages faster!

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools