search
HomeWeb Front-endJS TutorialAnalysis of improvements in the latest version of jQuery 1.5_jquery

The biggest update in version 1.5 is a complete rewrite of AJAX, providing greater scalability. However, due to energy and space constraints, the analysis of the new AJAX will be postponed to another time. This article will briefly introduce the detailed improvements.

jQuery._Deferred and jQuery.Deferred
First of all, I have to talk about these two new things, because they exist as infrastructure. If these two things are not explained clearly, some problems cannot be explained at all. .

First of all, jQuery.Deferred is an enhanced version of jQuery._Deferred, so for this problem, starting with jQuery._Deferred can explain most of the problem.

What is Deferred? Literally, my first reaction was "lazy loading". The first letter in capital letters should be the definition of "type", so this is probably a type that "transparently provides lazy loading function". However, in fact, although it does have a little bit of "delay" meaning, this thing is not used to implement lazy loading.

To put it simply, jQuery._Deferred is a function queue. Its functions are as follows:

Save several functions.
Execute all saved functions at a specific time.
After execution, the new function will be executed immediately.
Does it feel similar to something? Yes, jQuery's ready function has such logic. In fact, the ready function in jQuery 1.5 has indeed been grafted onto it.

jQuery._Deferred provides the following interface:

done: in the form of function(fn1, fn2, ...), used to add functions to the queue.
fire: In the form of function(context, args), use context to specify this object, args to specify parameters, and call all functions in the queue. After fire is called, _Deferred will enter the isResolved state, and future calls to done will not save the function, but call the function directly.
resolve: Equivalent to calling fire(this, arguments), a simplified method.
isResolved: Used to determine whether _Deferred is in the isResolved state. For details, refer to the explanation of the previous fire function.
cancel: Cancel the entire queue, so that no matter whether there is fire or not in the future, the functions in the queue will not be called again.
Now that jQuery._Deferred is explained clearly, let’s take a look at jQuery.Deferred. This thing is actually composed of two _Deferreds. The first is called deferred, which is used to store functions in the "normal" state; the second is called failDeferred, which is used to store functions in the "error" state. At the same time, jQuery.Deferred provides some new interfaces:

then: in the form of function(done, fail), add done to deferred and fail to failedDeferred.
fail: equivalent to the done function of failDeferred.
fireReject: equivalent to the fire function of failDeferred.
reject: Equivalent to the resolve function of failDeferred.
isRejected: Equivalent to the isResolved function of failDeferred.
At the same time, jQuery.Deferred cancels the cancel function.

So what is this used for? There are two states: "normal" and "error", and it is asynchronous at the same time. It is easy to think of... Yes, it is used for AJAX. I will explain it in detail in the next analysis.

Changes in jQuery.ready
Because of jQuery._Deferred, the jQuery.ready function becomes dependent on the function queue. The specific changes are:

The original readyList variable is no longer an array, but becomes a jQuery._Deferred object.

The original logic of calling all functions in readList when DOMContentLoaded is now also used in jQuery._Deferred. The original code:

Copy code The code is as follows:

while ( (fn = ready[ i ]) ) {
fn.call( document, jQuery );
}

becomes:
Copy code The code is as follows:

readyList .fire( document , [ jQuery ] );

jQuery.parseXML function
Added a new static function jQuery.parseXML to provide browser-compatible slave characters The function of converting string into XML document.

There are many logics for this function, and there is nothing special about jQuery. They are roughly divided into the following two types:

For standard browsers, use the DOMParser object:
Copy code The code is as follows:

var parser = new DOMParser();
var xml = parser.parseFromString(text , 'text/html'); For IE, use the Microsoft.XMLDOM object:

var parser = new ActiveXObject('Microsoft.XMLDOM');
parser.async = 'false';
parser.loadXML(text);
var xml = parser.documentElement;

data section
Added the jQuery.hasData function, which is used to determine whether an element has data attached by jQuery.

Modified the implementation of jQuery.expando. In addition to simply taking the current time, a random number was added:

expando = "jQuery" ( jQuery.fn.jquery Math. random() ).replace( /D/g, "" ); This ensures that multiple jQuery copies are introduced at the same time, and the expando between these copies will not conflict with each other, causing the data on the elements to become disordered. Generally speaking, multiple copies of jQuery will not be introduced, but when using SealJS, etc., such problems can easily occur if the configuration is improper.

DOM operation part
The original hasClass, addClass, and removeClass functions all need to separate the class attribute of the element into an array. In version 1.4.4, they are separated by n or. Added a new one in 1.5 , used to correspond to the newline character (rn) on the Windows platform.

jQuery.fn.attr function, in version 1.4.4, refuses to obtain attributes from TextNode and CommentNode, and in version 1.5, an AttributeNode (noteType == 2) is added.

In version 1.4.4, jQuery will clean up all DOM events maintained by jQuery when the page is unloaded. This is to avoid the memory leak problem of IE. But this piece of code disappeared in 1.5. I don’t know why.

Regarding the problem of using cloneNode to copy nodes under IE, events will also be copied together. In 1.4.4, the method was solved by copying innerHTML, while in 1.5, the method provided by the mootools team was adopted. Use the cloneFixAttribute function to fix this problem.

The cloneFixAttribute functions are located in lines 5388-5438 of the jQuery 1.5 beta1 source code file. The principle of dealing with IE bugs is very simple. Of course, some seemingly simple things in the front end are difficult to find:

There is a function called clearAttributes in IE, which will clear all attributes on the node. By the way, attributes such as onclick related to the event will also be removed. Calling this function on the copied node will clear the attributes.
There is also a function called mergeAttributes in IE, which copies the attributes of one node to another node, but it will not copy the attributes related to the event. So call mergeAttributes on the original node and put the attributes back on the copied node. This is equivalent to removing event-related attributes.
In addition, the cloneFixAttribute function also handles many compatibility issues of IE6-8 on cloneNode, which is worth studying in detail.

AJAX part
AJAX has been completely rewritten, leaving only a few corners to retain the style of version 1.4.4. Here, only a part is extracted for a brief explanation.

The implementations of $.get and $.post in the original version are very similar. Specifically, only one method configuration item is different, so it was merged in version 1.5:
Copy code The code is as follows:

$.each(['get', 'post'], function(i, method) {
$[method] = function() { ... };
});

The ajaxSetup function now adds a line of return this; and can be called in a chain.

The serializeArray function now uniformly replaces newline characters in value with Windows style (rn).

In the AJAX callback function, the object used as a parameter is no longer the native XMLHTTPRequest, but an object called jXHR encapsulated by jQuery itself. This object provides a common interface for XMLHTTPRequest.

Originally, in addition to 200-299 and 304, there is also a 1223 for the "request successful" browser status code. This comes from a BUG in IE that changes the 204 status code to 1223. Now because of the jXHR object, it is equivalent to an extra layer in the middle, so the statusCode obtained from the jXHR object will not appear as 1223, but has been changed back to 204.

There is an additional statusCode item in the configuration items of jQuery.ajax function. Its structure is map, which is used to specify the callback function when returning a specific status code. The general form is as follows:
Copy code The code is as follows:

jQuery.ajax({
url: 'xxx',
statusCode: {
200: function() {Processing request successfully},
404: function() {Processing page not found},
503: function() {Processing Service Unavailable}
}
}) ;

After adding this callback, the jQuery.ajax function already has a lot of callback functions. The triggering process is as follows:

Trigger the success or error callback based on the returned status code.
Trigger the corresponding statusCode callback based on the status code.
Trigger complete callback.
Trigger global ajaxComplete callback.
If there is no AJAX being executed at this time, trigger the global ajaxStop callback.
Other details
The entry function jQuery.fn.init now has an additional parameter, the value is always rootjQuery, which is used to speed up the search speed of the rootjQuery variable in the init function (reducing a layer of effect Domain):

//jQuery 1.5 beta1 source code line 23
jQuery = function( selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
}jQuery object support has been inherited. The specific modification is to change several codes that directly call jQuery into calls to this.constructor:

Line 202: return this.constructor( context ).find( selector );
Line 253: var ret = this.constructor();
Line 334: return this.prevObject || this.constructor(null) ;At the same time, the jQuery.subclass function is also provided to create a type that inherits from jQuery. Since jQuery is not very commonly used, and it has never been used to inherit jQuery, it is not convenient to say how useful this function is.
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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),