What’s New in jQuery 3.0 and How to Use It
This article is part of a web development series from Microsoft. Thank you for supporting the partners who make SitePoint possible.
jQuery, the world’s most popular JavaScript library to date, has been a boon for a lot of us web developers out there. From the time of its initial release in 2006 till today, a lot of us web developers have included this wonderful library in our projects to make our life easier.
Back in July 2015, jQuery announced the first alpha of jQuery 3.0 – a major release after a long time. Let’s take a look at what’s new in jQuery and how you can use it.
Update: This article is now updated to include the jQuery 3.0 beta release on 14 Jan, 2016.
show() and hide()
Update: jQuery had tried a new implementation in alpha, but have reverted that change in the 3.0 beta.
With the 3.0 beta, there’s now improved performance for hiding many elements. The jQuery team made the demo available here. One of the tests revealed this result:
The jQuery 2.0 version was up to 97% slower!
In addition to this, another suggested way to go about showing and hiding elements is to use addClass() and removeClass() to control visibility. Or we can call hide() on the elements during the ready() call.
Quick sample:
<!DOCTYPE HTML>
<html>
<head>
<style>
.invisible{
display: none;
}
.visible{
background-color: deepskyblue;
display:block;
}
</style>
<script src="jquery-3.0.0-beta1.js"></script>
<script>
$(document).ready(function(){
$("#div1").addClass("invisible");
$("#toggle").click(function(){
$("#div1").removeClass("visible");
$("#div1").addClass("invisible");
});
});
</script>
<title>Control Visibility</title>
</head>
<body>
<p>Hello!</p>
<div id="div1">Can you see this?</div>
<button id="toggle">Click me</button>
</body>
</html>
Nomenclature for .data() Key Names
The jQuery team changed the .data()
implementation to closely match the HTML5 dataset specification. If the key in the data-* attribute contains a digit, the digits will no longer participate in the conversion. Consider this example:
With jQuery 2.1.4:
The console window does not display the object.
With jQuery 3.0.0:
The key is converted to foo-42Name as digits do not participate in the conversion to camel case now. Hence, we get the output in console. The fiddle is available at https://jsfiddle.net/nWCKt/25/. You can change the jQuery versions to see the changes.
Similarly, if we want to display all the data using data()
with no arguments, the number of arguments will change in the two versions of jQuery if any of the key names of data-* attributes had a digit immediately after the hyphen (-), like in the above case.
HTML:
<div data-foo-42-name="namebar" data-foo-42-yes="yesbar"></div>
JavaScript:
var div = $('div');
console.log(div.data());
In jQuery 3.0, this would show the object {foo-42Name: “namebar”, foo-42Yes: “yesbar”}. But in an earlier version, it would show an empty object {}.
width() and height() return decimal values
Some browsers return subpixel values for width and height. jQuery now returns decimal values for .width()
, .height()
, .css(“width”)
, and .css(“height”)
whenever the browser supports it. For users looking for subpixel precision for designing webpages, this may serve as good news.
.load(), .unload(), and .error() methods are removed
These methods which were deprecated earlier, have now been removed from in jQuery 3.0.0 beta. The recommended way is to use .on()
to handle these events. Short example:
HTML:
<img src="space-needle.png" alt="Space Needle" id="spacen">
JavaScript:
Earlier implementation (now defunct)
$( "#spacen" ).load(function() {
// Handler implementation
});
Recommended implementation:
$( "#spacen" ).on( "load", function() {
// Handler implementation
});
jQuery Objects are Iterable Now
Iterating over jQuery objects is possible now, using ES2015 for-of. So, you can use things like:
for ( node of $( "<div id=spacen>" ) ) {
console.log( node.id ); // Returns ‘spacen’
}
(Source here)
jQuery Animations Now Use requestAnimationFrame API at the Backend
All modern browsers now support requestAnimationFrame
(status here: http://caniuse.com/#search=requestAnimationFrame). With its popular support, jQuery will use this API when performing animations. Advantages include smoother animations and less CPU-intensive animations (hence, saving battery on mobiles).
Enhancement of .unwrap() Method
.unwrap()
method, which lets you remove the parents of the matched elements from the DOM, did not use to accept parameters earlier. This could be an issue if someone wants to unwrap basis a condition set on the parent.
With jQuery 3.0.0 beta, .unwrap()
accepts the jQuery selector parameter to handle this.
jQuery.Deferred Updated to be Promises/A+ Compatible
A promise
is an eventual result of an asynchronous operation – it is an object that promises to deliver a result in future. The primary way of interacting with promise is through the then
method, which registers callbacks. Using Promise for asynchronous work in JavaScript is becoming increasingly popular these days. Promises/A+ is an open standard for interoperable JavaScript promises. (For more info, check out this link: https://promisesaplus.com/)
From jQuery documentation, the Deferred object is a chainable utility object created by calling the jQuery.Deferred()
method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. In jquery 3.0.0 beta, the jQuery.Deferred
objects are updated to be compatible with Promises/A+ and ES2015 Promises. Hence, there were major changes madeto .then()
method.
Better Handling of Error Cases
This version of jQuery has better handling of error cases – incorrect requests which have been ignored till now, throw up errors.
For example: Consider offset
, which gets the current coordinates of the first element, in the set of matched elements, relative to the document. If you were trying to find out the offset for a window with earlier versions of jQuery, you’d get the result as {top: 0, left: 0}
instead of an error being thrown, since the offset for a window does not make sense. With the 3.0 beta version, it will now throw up an error.
Another example: $("#")
now throws an error rather than returning 0-length collection.
Massive Speedups for Custom Selectors Like :visible
There have been massive performance improvements made when selectors like :visible are used in a document multiple times. Internally, this is done by caching – so the first time the selector is used, the result is the same. But, each call after that gives results way faster, since caching comes into play. Timmy Willison from jQuery reported that it leads to about 17x improvement for the :visible
selector!
These were among some of the major updates made. Entire list is available on their official blog: http://blog.jquery.com/2016/01/14/jquery-3-0-beta-released/.
Where to Download the Latest Version
There are two releases:
- You can get the latest version directly from: https://code.jquery.com/jquery-3.0.0-beta1.js
- The minified version is available from: https://code.jquery.com/jquery-3.0.0-beta1.min.js
It’s also available on npm:
npm install jquery@3.0.0-beta1
With Microsoft dropping support for IE8, IE9 and IE10, jQuery has dropped support for IE8 in jQuery 3.0. If you need IE6-8 support, you should use the latest 1.12 release.
Feel free to try out this beta version and give feedback on https://github.com/jquery/jquery. It’s worth a shot!
More Hands-on with Web Development
This article is part of the web development series from Microsoft evangelists and engineers on practical JavaScript learning, open source projects, and interoperability best practices including Microsoft Edge browser and the new EdgeHTML rendering engine.
We encourage you to test across browsers and devices including Microsoft Edge – the default browser for Windows 10 – with free tools on dev.microsoftedge.com:
- Scan your site for out-of-date libraries, layout issues, and accessibility
- Download free virtual machines for Mac, Linux, and Windows
- Check Web Platform status across browsers including the Microsoft Edge roadmap
- Remotely test for Microsoft Edge on your own device
More in-depth learning from our engineers and evangelists:
- Interoperability best practices (series):
- Coding Lab on GitHub: Cross-browser testing and best practices
- Woah, I can test Edge & IE on a Mac & Linux! (from Rey Bango)
- Advancing JavaScript without Breaking the Web (from Christian Heilmann)
- Unleash 3D rendering with WebGL (from David Catuhe)
- Hosted web apps and web platform innovations (from Kiril Seksenov)
Our community open source projects:
- vorlon.JS (cross-device remote JavaScript testing)
- manifoldJS (deploy cross-platform hosted web apps)
- babylonJS (3D graphics made easy)
More free tools and back-end web dev stuff:
- Visual Studio Code (lightweight code-editor for Mac, Linux, or Windows)
- Visual Studio Dev Essentials (free, subscription-based training and cloud benefits
- Code with node.JS with trial on Azure Cloud