Home  >  Article  >  Web Front-end  >  An introduction to some improved details of jQuery

An introduction to some improved details of jQuery

零下一度
零下一度Original
2017-06-19 11:08:10886browse

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: <pre class="brush:php;toolbar:false">while ( (fn = ready[ i++ ]) ) {       fn.call( document, jQuery ); }</pre> becomes: <pre class="brush:php;toolbar:false">readyList.fire( document , [ jQuery ] );</pre>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');

For IE, use the Microsoft.XMLDOM object:

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

data部分

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

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

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

这样保证在同一时间,引入多个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() { ... }; });

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 }     } });

再添加了这个回调后,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 ); }

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

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

同时还提供了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:
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