JQuery version upgrades

Source: Internet
Author: User

JQuery version upgrades

Background

--------------------------------------------------------------------------------

JQuery must be familiar to all web engineers, but now many websites still use the very old jQuery version. In fact, if an earlier version is used improperly, the DOMXSS vulnerability may occur. We recommend that you upgrade it to jQuery 1.9.x or later. Some time ago, I took the lead in this case and upgraded the jQuery version of the project in our group from 1.4.2 to jQuery 1.11.3. JQuery also provides the jQuery Migrate plug-in for similar upgrades.

Let's get down to the truth.

Where did the pitfalls come from?

--------------------------------------------------------------------------------

JQuery 1.11.3 is 1. the last version of the x era (updated by the author: jQuery 1.12.0 was launched in January 8, 2016, and jQuery 1.11.3 is no longer 1. the last version of the x era). Because my department project has been in use for some years, jQuery 1.4.2 was adopted at that time. This upgrade step is relatively large. In the early days, many jQuery statements were discarded in the new version, or some non-standard statements. At that time, the version was still supported, but not yet supported. Even worse, the new version is still supported, but the features are different from those before ...... In this case, an error is not reported, and you need to go deep into the code logic.

JQuery officially recommends the jQuery Migrate library to solve the jQuery upgrade problem. However, it is not a long term to use this library. We recommend that you use the development version of jQuery Migrate during development. You can print out the incompatible details on the browser console. It should be noted that the development version of jQuery Migrate must be used in development, because the compressed version will not give a warning on the console ...... REFERENCE The jQuery Migrate library immediately after the jQuery Library:

<script src="<path>/<to>/jquery-1.11.3.js"></script><script src="<path>/<to>/jquery-migrate-1.2.1.js"></script> 

After the upgrade is complete, confirm that there is no problem, and then remove the jQuery Migrate library. Based on my personal experience, I will divide the pitfalls into common pitfalls and discuss them in two ways.

Common pitfalls

--------------------------------------------------------------------------------

1. the discarded jQuery. fn. live method is used.

The jQuery Migrate Library also has a warning on this error in the console:

JQMIGRATE: jQuery. fn. live () is deprecated
The original function of the live method is to set the event proxy. This method is not recommended after jQuery 1.7, instead of the jQuery. fn. on function. Their interfaces are:

$(selector).live('click', function(){/* some code */});$(selector).on('click', [selector,] function(){/* some code */}); 

At first glance, the parameters in brackets can be omitted. aren't the two functions identical? Therefore, the function name live is replaced directly with on. In most cases, this action does not seem to cause any exceptions. However, if you call the on function, the previous $ (selector) the current webpage does not match any element at all (this element may be added to the DOM only by the code below), and it will not be successfully bound. In fact, the live function proxies $ (selector) to the document element, which certainly exists, so similar situations will not occur. The correct replacement method should be:

$ (Selector ). live ('click', function () {/* some code */}); Replace with $ (document ). on ('click', selector, function () {/* some code */});

2. the discarded jQuery. fn. die method is used.

JQuery Migrate's warning for this error is:

JQMIGRATE: jQuery. fn. die () is deprecated

This method is the opposite of the previous live method, canceling the binding of event processing functions. The new version should be replaced by the off function. The replacement method is similar.

3. Used the obsolete jQuery. fn. toggle Function

JQuery Migrate's warning for this error is:

JQMIGRATE: jQuery. fn. toggle (handler, handler...) is deprecated

In early jQuery, there were two functions named toggle. One was used to control the display and hiding of elements. Currently, this function still exists in jQuery; the other is the discarded toggle function mentioned above. It is used to bind at least two functions to the same element. When you click this element, the two functions are executed alternately. These two functions of the same name are far different. To avoid misleading functions, we do not recommend them in jQuery 1.8. The replacement method is to combine the two functions into the if-else two sections of a function, and then set a boolean variable to control which segment should be executed during each click.

4. the discarded jQuery. browser attribute is used.

JQuery Migrate's warning for this error is:

JQMIGRATE: jQuery. browser is deprecated

In front-end development, we often need to make different processing based on different browser versions. jQuery. browser uses the browser's userAgent field to extract browser-related information. In the new version, we recommend that you use the feature detection method to determine whether to use it, and provide a Modernizr library as a recommendation. However, it may be a little costly to change to this library. If you still want to follow the jQuery. browser idea, you can implement it on your own. For example, you can use

/Msie/. test (navigator. userAgent. toLowerCase ());

That is, manually obtain the userAgent field and make a regular expression match. Similar to other browsers, the idea is to make a regular match for navigator. userAgent.

5. $ (html) format incorrect writing

In jQuery Migrate, any of the following three warnings is an error:

JQMIGRATE: $ (html) HTML strings must start with '<'character
JQMIGRATE: $ (html) HTML text after last tag is ignored
JQMIGRATE: HTML string cannot start with a' # 'character

This error is worth noting because the earlier jQuery versions mentioned at the beginning of this article have the XSS vulnerability, which is actually related to this error. In javascript, we often directly write an html string in jQuery reference, for example, $ ('<div> </div> '). According to the requirements of the new jQuery version, the html string must start with a left angle bracket (smaller than the number). other characters are not allowed. The following statements are incorrect:

$ ("<Div> </div>"); // error. There is a space at the beginning of the string, not starting with a sign '<'
$ ("<Div> </div> test"); // not standard. Additional "test" is added after the html Tag ends, which is ignored.
$ ("# <Div> </div>); // error. It starts with a well number and is not followed by a css selector.

This can be avoided easily when writing. Among them, the third error is not just a warning. jQuery will directly throw an error and stop javascript code execution. Generally, it starts with a well number. For example, $ ("# test") is actually a common selector, but the preceding example is followed by an html string, this is determined by jQuery as a potential XSS attack.

6. jQuery. fn. attr (this is a very easy mistake !)

In jQuery Migrate, there are the following warnings about the attr method:

JQMIGRATE: jQuery. fn. attr ('value', val) no longer sets properties
JQMIGRATE: jQuery. fn. attr ('value') no longer gets properties
JQMIGRATE: jQuery. fn. attr ('checked') may use property instead of attribute
JQMIGRATE: jQuery. fn. attr (props, pass) is deprecated

In practice, I found that in the code written earlier, how did I obtain the value of an input form? $ ('Input'). attr ('value'); how is it set? $ ('Input'). attr ('value', 'helloworld '). This is incorrect in the new version! The correct method should be

$ ('Input'). val (); // obtain the value currently entered in the input form
$ ('Input'). val ('helloworld'); // sets the input value of the input form.

Whether it is obtained or set depends on whether the val method is called without parameters.

If you want to manually set a single sequence (for example, <input type = "radio">) to be selected, how should you set it? The old code may see this $ ('input '). attr ('checked', true) or $ ('input '). attr ('checked', 'checked '). These are also incorrect! The correct method should be

$ ('Input'). prop ('checked', true); // set a ticket to the selected status.
$ ('Input'). prop ('checked'); // returns true or false if a single token is selected.

This is the method used since jQuery 1.6. If the disabled and selected attributes are set, the prop method is also used. When will the attr method be used? The difference between the two is that prop sets the inherent attributes of an element, while attr sets the Custom Attributes written on the html Tag. For example:

<Input type = "checkbox" checked = "checked" haha = "hello"> var v1 =$ ('input '). prop ("checked"); // return true/false, whether it is selected, change var v2 as the status changes = $ ('input '). attr ("checked"); // return "checked", which is set on the tag and does not change var v3 =$ ('input '). attr ("haha"); // return "hello", custom attribute var v4 =$ ('input '). prop ("haha"); // return undefined, no such inherent attribute

The fourth error mentioned above, jQuery. fn. attr (props, pass) is deprecated, which has never been seen in real projects. After reading the source code, jQuery statements that trigger this warning are rare and can be ignored.

7. Invalid parameters are passed into $. parseJSON.

In jQuery Migrate, this error generates the following warning:

JQMIGRATE: jQuery. parseJSON requires a valid JSON string

JQuery modifies this interface to align with the browser's built-in JSON. parse interface, which takes effect from jQuery 1.9. This problem occurs when AJAX receives the return value from the server. The server may return an empty string. An error occurs when this interface is called. You must input a valid JSON string to $. parseJSON. The correction method is as follows:

Var v1 = $. parseJSON (str); Replace with var v1 = $. parseJSON (str? Str: "null ");

8. The discarded 'hover 'event string is used.

In jQuery Migrate, this error generates the following warning:

JQMIGRATE: 'hover 'pseudo-event is deprecated, use 'mouseenter mouseleave'

When registering an event processing function, 'hover 'can be considered as the alias for the two events 'mouseenter mouseleave. This alias has been removed, so replace it with 'mouseenter mouseleave 'in the code.

9. jQuery. fn. andSelf has been replaced and cannot be used any more.

In jQuery Migrate, the following warning is displayed:

JQMIGRATE: jQuery. fn. andSelf () replaced by jQuery. fn. addBack ()

The two functions are identical and can be replaced directly.

The above are common problems in jQuery upgrade. Of course, in the spirit of perfection, we still need to study what the uncommon problems look like. It should be pointed out that the following problems have never been encountered in my actual project and are rare, but they cannot be guaranteed that they will not appear in your project, it is only for reference by interested programmers.

Rare pitfalls

--------------------------------------------------------------------------------

1. jQuery is incompatible with the weird browser Mode

The trigger method for this error is very simple, and the top of the html page is directly <! Delete the DOCTYPE html> tag. The weird browser mode is designed to be compatible with old-fashioned web pages. For details, refer to this article: link. I think the current WEB programmers should not be stupid enough to not write DOCTYPE, and rarely use browsers in this mode.

The error message displayed by jQuery Migrate is as follows:

2. AJAX global events must be bound to the document node.

The warning in jQuery Migrate is as follows:

JQMIGRATE: AJAX events shoshould be attached to document: ajaxStart

In jQuery, AJAX global events include the following interfaces: ajaxStart, ajaxStop, ajaxSend, ajaxComplete, ajaxError, and ajaxSuccess. These events are rarely used, so they are rarely used. From jQuery 1.9, these events can only be bound to $ (document. The correct method is as follows (from the jQuery official website ):

$ ("# Status "). ajaxStart (function () {$ (this ). text ("Ajax started") ;}; change to $ (document ). ajaxStart (function () {$ ("# status "). text ("Ajax started ");});

3. The IE6/7/8 browser does not support modifying the type attribute of the input form.

In jQuery Migrate, the following warning is displayed:

JQMIGRATE: Can't change the 'type' of an input or button in IE 6/7/8

To change the type attribute of the input form, you can directly change the text box to single-choice and multi-choice. Although I think this is not elegant, many browsers support this, except IE6/7/8. We recommend that you use this function less in practice.

4. removed $. clean, $. event. handle, $. attrFn, $. fn. data ('events'), jQuery. event. trigger attributes and methods are used.

In jQuery Migrate, the following warning is displayed:

JQMIGRATE: jQuery. clean () is deprecated
JQMIGRATE: jQuery. event. handle is uninitialized ented and deprecated
JQMIGRATE: jQuery. attrFn is deprecated
JQMIGRATE: Use of jQuery. fn. data ('events') is deprecated
JQMIGRATE: Global events are uninitialized ented and deprecated

If you have used these five interfaces in your code, you have carefully studied jQuery source code. These five interfaces have never been shown in jQuery's official documentation, and some of them have been deleted in subsequent versions. If you look at the source code, you will have a chance to find them in earlier versions, but it is not recommended. We recommend that you use other methods to implement the corresponding functions. What? You don't know what these five functions are? That's the best thing. You don't need to know it now ......

5. the outdated $. sub () method is used.

In jQuery Migrate, the warning for this problem is as follows:

JQMIGRATE: jQuery. sub () is deprecated

This interface is very simple and does not accept any parameters. It is used to create a copy of jQuery. This method is no longer used since jQuery 1.7.

6. the obsolete jQuery. fn. error method is used.

In jQuery Migrate, the warning for this problem is as follows:

JQMIGRATE: jQuery. fn. error () is deprecated

In jQuery, error is the same as click. Registers the event's processing function, previously $ (selector ). error (function () {}), which has been deprecated now. You can use $ (selector ). on ('error', function.

Sample Code

--------------------------------------------------------------------------------

Since this article is called "XX Daquan", it should be as comprehensive as possible. To understand how these pitfalls are entered, we finally write a piece of js Code, which requires that all the pitfalls in the jQuery Migration library be repeated with the least code ...... That is, let the jQuery Migration library print out all the code that it can print. The final code is as follows (the blog garden cannot upload attachments and can only paste code), which is easy to understand. Open the index.html file and press the F12 key to open the console. Then you can see the spectacular console warning ^_^

<! -- Filename: index.html --> <! -- <! DOCTYPE html> --> // keng0 weird mode 


Articles you may be interested in:
  • The selector syntax after Jquery upgrades the new version
  • JQuery1.3.2 upgrade to jQuery1.4.4 where modification is required
  • Jquery animation 4. Image corridor with upgraded masked effects-with Automatic Running Effect
  • Upgrade the previously written jquery pagination

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.