Table of Contents
jQuery._Deferred and jQuery.Deferred
object:
data部分
AJAX部分
其他细节
Home Web Front-end JS Tutorial An introduction to some improved details of jQuery

An introduction to some improved details of jQuery

Jun 19, 2017 am 11:08 AM
jquery introduce Improve detail

jquery API”>jQuery 1.5 beta1 is out. In terms of learning and follow-up, this time it is relatively late (I don’t even know when 1.5 came out as alpha, so it is just beta).

The biggest update of version 1.5 is the complete rewriting of AJAX, which provides stronger scalability. However, due to energy and space constraints, the analysis of the new AJAX will be left to another time. This article will briefly introduce the details. Improvements.

jQuery._Deferred and jQuery.Deferred

First of all, I have to talk about these two new things, because they exist as infrastructure, and I don’t understand these two things clearly. Some problems cannot be explained at all.

jQuery.Deferred

is an enhanced version of jQuery._Deferred, so for this problem, start with jQuery._Deferred. It will explain most of the problem What is Deferred? Literally, my first reaction is "lazy loading", the first letter should be the definition of "type". , so this is probably a type of "transparently providing 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

##. #Simply put,

jQuery._Deferred

is a function queue. Its functions are as follows:

##Save several functions.

    Execute all the saved functions at a specific time.
  • ##After execution, the new incoming functions will be executed immediately.
  • #Does it feel similar to something? Yes, jQuery's ready function has this kind of logic. In fact, the ready function in jQuery 1.5 has indeed been grafted onto it.
  • jQuery._Deferred
  • provides the following interface:
done

:

function(fn1, fn2, …)

, in the form To add a function to the queue

    ##fire
  • :

    function(context, args), use context##. #Specify this object,

    args
  • specify parameters, and call all functions in the queue. After
  • fire

    is called, _Deferred will enter the isResolved state. Future calls to done will no longer 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, please refer to the explanation of the previous fire function. .

  • cancel

    : Cancel the entire queue, so that no matter whether fire occurs in the future, the functions in the queue will not be called again. Now that

    jQuery._Deferred
  • is explained, let’s take a look at
  • jQuery.Deferred

    . This thing is actually composed of two _Deferreds. The first one is called deferred, which is used to store functions in the "normal" state; the second one is called failDeferred, which is used to store functions in the "normal" state. Save functions in "error" state. At the same time,

    jQuery.Deferred
  • provides some new interfaces:

then: function(done, fail) In the form, 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 of "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 the
jQuery._Deferred

, the jQuery.ready function becomes dependent on the function queue, specifically The changes include: The original

readyList

variable is no longer an array, but has become a

jQuery._Deferred

object.

Originally in DOMContentLoaded, the logic of calling all functions in readList is now also used in

jQuery._Deferred

, the original code: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">while ( (fn = ready[ i++ ]) ) {       fn.call( document, jQuery ); }</pre><div class="contentsignin">Copy after login</div></div> becomes: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">readyList.fire( document , [ jQuery ] );</pre><div class="contentsignin">Copy after login</div></div>jQuery.parseXML function

Added static function jQuery.parseXML to provide browser-compatible Function to convert string to XML document. There are many logics for this function on the Internet, and there is nothing special about jQuery. They are roughly divided into the following two types:

For standard browsers, use the

DOMParser

object:

var parser = new DOMParser();   var xml = parser.parseFromString(text, 'text/html');
Copy after login

For IE, use the Microsoft.XMLDOM object:

data部分

添加了jQuery.hasData函数,用于判断一个元素是否有jQuery附加上去的数据。

修改了jQuery.expando的实现,在原来单纯地取当前时间的基础上,添加了一个随机数:

expando = "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( //D/g, "" );
Copy after login

这样保证在同一时间,引入多个jQuery副本,这几个副本之间的expando不会相互冲突,导致元素上的data变得错乱。一般来说,是不会引入多个jQuery副本的,但是使用SealJS等的时候,配置不当的话,也是很容易出现此类问题的。

DOM操作部分

原本的hasClassaddClassremoveClass函数都需要将元素的class属性分隔为数组,在1.4.4版本中,通过/n或/t进行分隔,在1.5中增加了一个/r,用于对应Windows平台下的换行符(/r/n)。

jQuery.fn.attr函数,1.4.4版本中拒绝从TextNode和CommentNode上获取属性,在1.5版本中添加了一个AttributeNode(noteType == 2)。

在1.4.4版本中,jQuery会在页面unload的时候清理掉由jQuery维护的所有DOM事件,这是为了避免IE的内存泄露问题。但是在1.5中这一段代码不见了,不知是出于什么考虑。

对于IE下使用cloneNode复制节点,会将事件也一起复制过来的问题,1.4.4中是采取复制innerHTML的方式给予解决,而在1.5中则采纳了mootools团队提供的方法,使用cloneFixAttribute函数修正该问题。

cloneFixAttribute函数们于jQuery 1.5 beta1源码文件的5388-5438行,处理IE的BUG的原理很简单,当然前端里一些看似简单的东西,都是很难发现的:

  • IE中有个叫clearAttributes的函数,会清除到节点上的所有属性,顺便把和事件相关的<a href="http://www.php.cn/wiki/1449.html" target="_blank">onclick</a>之类的属性也去掉了。在复制出来的节点上调用这个函数,就会把属性清得干干净净。

  • IE中还有一个叫mergeAttributes的函数,把一个节点的属性复制到另一个节点上,但他不会把和事件相关的属性复制过去。所以再把原始节点调用mergeAttributes,把属性重新放回复制出来的节点上,这就相当于起到了去除事件相关属性的作用。

另外cloneFixAttribute函数还处理了非常多IE6-8在cloneNode上的兼容性问题,非常值得详细研究。

AJAX部分

AJAX已经完全重写了,只留下一点边边角角保留着1.4.4版本的风采,这里只抽取一部分进行简单的说明。

原来版本中$.get$.post的实现非常相似,具体来说仅有一个method配置项不同,因此在1.5版本中被合并起来了:

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

ajaxSetup函数现在加了一行return this;,可以链式调用了。

serializeArray函数现在统一将value中的换行符替换成Windows的风格(/r/n)。

AJAX的回调函数中,作为参数的对象不再是原生的XMLHTTPRequest,而是jQuery自己封装的称为jXHR的对象,这个对象提供了XMLHTTPRequest的常用接口。

原本对于“请求成功”的浏览器状态码,除200-299以及304外,还有一个1223,来自于IE的一个BUG,会将204的状态码变成1223。现在因为有了jXHR对象,相当于中间多了一层,因此从jXHR对象获取statusCode不会出现1223的情况,已经被变回204了。

jQuery.ajax函数的配置项中多了一个statusCode项,其结构为map,用于指定返回特定状态码时的回调函数,大致形式如下:

jQuery.ajax({       url: 'xxx',     statusCode: {         200: function() { 处理请求成功 },         404: function() { 处理页面未找到 },         503: function() { 处理Service Unavailable }     } });
Copy after login

再添加了这个回调后,jQuery.ajax函数已经有非常多的回调函数,其触发过程如下:

  1. 根据返回的状态码,触发success或者error回调。

  2. 根据状态码,触发对应的statusCode回调。

  3. 触发complete回调。

  4. 触发全局ajaxComplete回调。

  5. 如果此时没有正在执行的AJAX,触发全局ajaxStop回调。

其他细节

入口函数jQuery.fn.init现在多了一个参数,值始终为rootjQuery,用于加速init函数中对rootjQuery变量的查找速度(减少了一层作用域):

// jQuery 1.5 beta1 源码23行 jQuery = function( selector, context ) {       // The jQuery object is actually just the init constructor 'enhanced'     return new jQuery.fn.init( selector, context, rootjQuery ); }
Copy after login

jQuery对象支持继承了,具体的修改是将几处直接调用jQuery的代码改为了对this.constructor的调用:

// 202行:     return this.constructor( context ).find( selector ); // 253行:     var ret = this.constructor(); // 334行: return this.prevObject || this.constructor(null);
Copy after login

同时还提供了jQuery.subclass函数用于创建一个继承自jQuery的类型,由于不是很常用jQuery,更是从来没有用到过需要继承jQuery的情况,因此也不方便说这个功能的作用有多大。

The above is the detailed content of An introduction to some improved details of jQuery. 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)

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Improvements in PHP7: no more undefined errors Improvements in PHP7: no more undefined errors Mar 04, 2024 pm 06:15 PM

Improvements in PHP7: No more undefined errors. PHP7 is a major version update of the PHP language, which brings many important improvements and optimizations. One of the significant improvements is that undefined errors no longer appear when dealing with undefined variables, which brings a better user experience to developers. Before PHP7, if undefined variables were used in the code, an undefined error would occur. Developers needed to manually check or set the error reporting level to avoid this situation.

Introduction to the eighth color weapon of Neon Abyss Introduction to the eighth color weapon of Neon Abyss Mar 31, 2024 pm 03:51 PM

The eighth color is a weapon in Neon Abyss. Many players want to know about the ballistics of the eighth color of the weapon and how to play with the weapon strength. So let’s take a look at the detailed guide to Neon Abyss’ eighth color weapon trajectory, weapon strength, and weapon gameplay. Neon Abyss Color 8 Detailed Guide Weapon Introduction: The Wizard’s Secret Weapon! Weapon attack speed: Normal Weapon strength: Moderate Weapon gameplay: The attack method of the eighth color is three single-target attacks and then launches a ray. Ballistic display:

Introduction to the online score checking platform (convenient and fast score query tool) Introduction to the online score checking platform (convenient and fast score query tool) Apr 30, 2024 pm 08:19 PM

A fast score query tool provides students and parents with more convenience. With the development of the Internet, more and more educational institutions and schools have begun to provide online score check services. To allow you to easily keep track of your child's academic progress, this article will introduce several commonly used online score checking platforms. 1. Convenience - Parents can check their children's test scores anytime and anywhere through the online score checking platform. Parents can conveniently check their children's test scores at any time by logging in to the corresponding online score checking platform on a computer or mobile phone. As long as there is an Internet connection, whether at work or when going out, parents can keep abreast of their children's learning status and provide targeted guidance and help to their children. 2. Multiple functions - in addition to score query, it also provides information such as course schedules and exam arrangements. Many online searches are available.

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

See all articles