JQuery upgrades and pitfalls

Source: Internet
Author: User

JQuery upgrades and pitfalls
JQuery upgrades

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 itCommon pitfalls,Rare pitfallsTwo types.

Common pitfalls 1. the discarded jQuery.fn.liveMethod

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

JQMIGRATE: jQuery.fn.live() is deprecated

liveThe original function of the method is to set the event proxy. This method is not recommended after jQuery 1.7. InsteadjQuery.fn.onFunction. 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, when you call the on function$(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$(selector)Proxy arriveddocumentThis element certainly exists on the element, 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.dieMethod

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. the discarded jQuery.fn.toggleFunction

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.browserAttribute

JQuery Migrate 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.browserThe userAgent field of the browser is used to extract information about the browser. 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 expensive to change the database.jQuery.browserYou can implement it by yourself. 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 browsersnavigator.userAgentMake a regular match.

5. $(html)Incorrect format

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

1. JQMIGRATE: $(html) HTML strings must start with '<' character2. JQMIGRATE: $(html) HTML text after last tag is ignored3. 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 a string in html format in jQuery reference, such$('<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:

1. $ ("<div> </div>"); // error. There is a space at the beginning of the string, not 2 starting with a sign '<. $ ("<div> </div> test"); // not standard. There is a redundant "test" after the html Tag ends. It will be ignored 3. $ ("# <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. It generally starts with a well number, for example$("#test")It is actually a common selector, but the above example is followed by an html string, which will be determined by jQuery as a potential XSS attack.

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

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

1. JQMIGRATE: jQuery.fn.attr('value', val) no longer sets properties2. JQMIGRATE: jQuery.fn.attr('value') no longer gets properties3. JQMIGRATE: jQuery.fn.attr('checked') may use property instead of attribute4. 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 (); // get the current input value of 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 region (for example<input type="radio" >) Is selected, how should I set it? You may see this in the old code.$('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 state $ ('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 deprecatedThis warning 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. Forward $.parseJSONThe specified parameter is invalid.

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. Required$.parseJSONInput a valid JSON string. 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.andSelfAlready replaced and cannot be used again

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 noted that:The following problems have never been encountered in my actual project.It is rare, but it cannot be guaranteed that it 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.<!DOCTYPE html>Delete the 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 should be attached to document: ajaxStart

In jQuery, AJAX global events include the following interfaces:ajaxStart,ajaxStop,ajaxSend,ajaxComplete,ajaxError,ajaxSuccess. These events are rarely used, so they are rarely used. From jQuery 1.9, these events can only be bound$(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.triggerAttributes and Methods

In jQuery Migrate, the following warning is displayed:

1. JQMIGRATE: jQuery.clean() is deprecated2. JQMIGRATE: jQuery.event.handle is undocumented and deprecated3. JQMIGRATE: jQuery.attrFn is deprecated4. JQMIGRATE: Use of jQuery.fn.data('events') is deprecated5. JQMIGRATE: Global events are undocumented 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. Outdated $.sub()Method

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. Outdated jQuery.fn.errorMethod

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

JQMIGRATE: jQuery.fn.error() is deprecated

In jQuery,errorAndclickSame event. The handler for registering this event. Previously$(selector).error(function(){})And can be used.$(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 to say, let the jQuery Migration library print out all the warnings 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

 

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.