To jQuery

or

Not to jQuery

  What is jQuery

jQuery is not a seperate language it's a framework built on top of javascript

Released in 2006 by John Resig based on a bunch of helpers he regularly used.

 

He deveoped coz existing libs were not good enough or modified js itself

 

It became a instant hit and is now used by over 80% of internet

 

Its being developed by some of the brightest minds and supported by some great companies

Developed in the Wild Wild West of the browser land

Say no to jQuery

 JavaScript Advantages

  • No extra libaries needed
  • 50-100x Faster 
  • Easy to Debug
  • If you know C  or  JAVA you know JavaScript
  • It's not just for dom or ajax or animation

over jQuery

Main anti-JS arguments:

  1. Inconsistent 
    write once is not run everywhere.
     
  2. Missing  features
    common everyday jQuery features missing.
     
  3. Difficult
    not my cup of tea.
     

Browsers support most things now

and that too in a simple way

Selecting Items

// '.classes', '[attributes]', '#ids'
document.querySelector(elem); 
document.querySelectorAll(elems);
// '.classes', '[attributes]', '#ids'
$(elem);

jQuery

JavaScript

Code

Performance

85%  - source

Support

93%   - source

Manuplating Classes

// JavaScript uses a DOMTokenList to contain
// the class names, returned via the classList Object
elem.classList.add('fowd');
elem.classList.remove('fowd');
elem.classList.toggle('fowd');
//You can use below method to a jQuery Object
$(elem).addClass('fowd');
$(elem).removeClass('fowd');
$(elem).toggle('fowd');

jQuery

JavaScript

Code

Performance

85%  -  source

Support

82%   -  source

el.className = el.className.replace(new RegExp('(^|\\b)' +
               className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
el.className += ' ' + className;

Add Class

Remove Class

Alt Code

Support

99%

Manuplating Attributes

elem.setAttribute('data-jquery', 'test'); // set
elem.getAttribute('data-jquery'); // get
$(elem).attr('data-jquery', 'test'); // set
$(elem).attr('data-jquery'); // get

jQuery

JavaScript

Code

Performance

86%  -  source

Support

99% 

Event Listners

if (el.addEventListener) {
    el.addEventListener(eventName, someFunction);
} else { //IE 8-
    el.attachEvent('on' + eventName, function(){
      someFunction.call(el);
    });
}
$(elem).on('click', someFunction);

jQuery

JavaScript

Code

94%   -  source

Performance

99%  -  source

Support

DOM Ready

document.addEventListener('DOMContentLoaded', Function_Name);
$(document).ready(Function_Name);

jQuery

JavaScript

Code

Performance

Performance Stats have, by now, become a joke

Support

89%   -  source

Styling Elements

// extend the Style Object, pure write, no loops
var elem = document.querySelector(elem);
elem.style.background = '#000';
elem.style.color = '#fff';
// creates an Object, will loop internally
$(elem).css({
  "background" : "#000",
  "color" : "#fff"
});

jQuery

JavaScript

Code

Support

99%

Loops

Code - nodes

var paragraphs = document.querySelectorAll( "p" );

for (var i = 0; i < paragraphs.length; i++ ) {
    paragraphs[ i ].classList.add('red');
};
jQuery('p').each(function(index, value) {
   jQuery(this).addClass('red');
});

//or jQuery('p').addClass('red')

jQuery

JavaScript

var arr = [2, 3, 5, 7];
arr.forEach(function (value, index) {
  //works ie9+ or use normal for loops
});
var arr = [2, 3, 5, 7];
$.each(arr, function(index, value) {
   
});

jQuery

JavaScript

Code - array

var obj = { a:'1', b:'2' };
for (var prop in obj) {

}
var obj = { a:'1', b:'2' };
$.each(obj, function(index, value) {
  
});

jQuery

JavaScript

Code - objects

And Lot More

Time Taken By Browsers to parse jQuery

  • Desktop       - 10-20 ms
  • Mobile         -  50-100 ms
  • Android 4.0 -  500ms

jQuery Core File Size

  • 1.11.0 : 32.64 KB
  • 2.1.0   : 28.66 KB

(minified and gzipped)

The slow parsing  of scripts on mobile browsers like Android forces us to use small JavaScript libraries.

Pick a micro-lib that pollyfils the feature

but remember to pick the right one

"The simplest (and safest) classes of cross-browser fixes are those that exhibit two important traits:

  • They have no negative effects or side effects on other browsers.
  • They use no form of browser or feature detection. "

Cross-browser Fixes

Say yes to jQuery

 jQuery Advantages

  • Cross-browser Compatibility
  • Short Learning curve
  • Great Documentation
  • Tons of Plugins
  • Unobtrusive by Design
  • Makes Javascript as easy as pie

Main anti-jQuery arguments:

  1. API Parity
    The Browsers mostly do everything now.
     
  2. Too Big / Bloated
    File size is too big, especially for mobile.
     
  3. Speed
    Native is faster.
     

Does Browser Support Everything

/*
 * Optional (non-Sizzle) selector module for custom builds.
 *
 * Note that this DOES NOT SUPPORT many documented jQuery
 * features in exchange for its smaller size:
 *
 * Attribute not equal selector
 * Positional selectors (:first; :eq(n); :odd; etc.)
 * Type selectors (:input; :checkbox; :button; etc.)
 * State-based selectors (:animated; :visible; :hidden; etc.)
 * :has(selector)
 * :not(complex selector)
 * custom selectors via Sizzle extensions
 * Leading combinators (e.g., $collection.find("> *"))
 * Reliable functionality on XML fragments
 * Requiring all parts of a selector to match elements under context
 *   (e.g., $div.find("div > *") now matches children of $div)
 * Matching against non-elements
 * Reliable sorting of disconnected nodes
 * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit)
 *
 * If any of these are unacceptable tradeoffs, either use Sizzle or
 * customize this stub for the project's specific needs.
 */

Browser Issues Fixed 

Browser Count
IE (all) 50
IE 10, 11 9
Firefox 10
Webkit 20
Android 7
IOS

2

Chrome

2

Opera

6

Safari

2

Reducing size

 Only what you need

  • jQuery, jQuery UI, jQuery Mobile all Supports AMD
  • Include only what you need
  • Use grunt to achieve your own download builder for jQuery similar to jQuery UI

 Better Compresstion

  • Google's Zopfil is a drop in replacement for defalte
  • It leads to an additional saving of 3.3% for 1.11
  • Works across all browsers

Size Doesn't Matter

Importance of reducing Round Trips

  1. In 2012, the average mobile RTT (Round Trip Time) time was 344ms in the US and 372ms in the UK.
     
  2. In 2012 the average mobile download throughput was 1.6 Mbps in the US and 1.4 Mbps in the UK.

Reducing RTT = Faster Site

Minimizing HTTP Request


80% of the end-user response time is spent on the front-end downloading all the components in the page: images, css, scripts  etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages.

YSlow

How about
loading jQuery from a 3rd party CDN

ajax.googleapis.com or code.jquery.com

" 81.9% of the websites use none of the JavaScript content delivery networks that we monitor.


Google Hosted Libraries is used by 15.8% of all the websites, that is a JavaScript content delivery network market share of 87.3%. "

w3techs

Cache Hits are rare

  • DNS lookup
  • TCP connection
  • HTTP GET

miss leads to 3 RTTs!

Less HTTP Request = Faster Site

Speed

in the Real World

Native methods will almost always be faster, but in the vast majority of cases it doesn't matter.


"I tried using the browser’s native innerHtml and getElementByClassName API methods instead of jQuery’s html and append. I thought native APIs might be easier for the browser to optimize and what I read confirmed that. But for whatever reason, it didn’t make much of a difference for Trello."

 

jQuery optimises common code path

// Easily-parseable/retrievable ID or TAG or CLASS selectors
var rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/;

// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
    // Speed-up: Sizzle("#ID")
    if ( (m = match[1]) ) {
        ...
    }

    // Speed-up: Sizzle("TAG")
    } else if ( match[2] ) {
        ...
    }

    // Speed-up: Sizzle(".CLASS")
    } else if ( (m = match[3]) && support.getElementsByClassName 
                 && context.getElementsByClassName ) {
        ...
    }
}

What about Zepto

  • Zepto is a jQuery-compatible lib.
  • APIs provided match their jQuery counterparts but not 100%
  • It's a drop-in replacement of jQuery for most projects
  • It's 1/4 the size of jQuery. 

But does it lead to faster site

" we found that lighter file size did not translate into better performance overall. Sure, Zepto downloaded quickly. But once loaded, it wasn't quite as fast as jQuery. It didn't help that many third-party plugins required jQuery, not Zepto — in fact, we found that some third party JavaScripts conflicted outright with Zepto."

jQuery is flexible 

var contentID = document.getElementById('contents'); //returns a HTML DOM Object
var contents = $(contentID);  //returns a jQuery Object

var contents = $('#contents')[0]; //returns a HTML DOM Object




$('p').each(function() {
    this.classList.add('red'); 
});

if something is slow use plain js. Mix and match for performance

2 cents

Think twice before using jQuery 

  • Single button with a click handler or loading a single iFrame
  • You are just changing a few classes or other properties
  • Plugins
  • Single browser extention
  • No <IE10 support and Android <4

in following cases

At the very least, make sure you know what jQuery is doing for you, and what it's not.

- Hubspot

Now You Decide

To jQuery

or

Not To jQuery

Thank You

Worry about the size of jQuery after you have

  • minified your assets,
  • concatenated your assets,
  • gziped your assets,
  • set appropriate cache headers,
  • removed unnecessary HTTP requests as much as possible (e.g. images)
hostname percentage 
ajax.googleapis.com 18.3%
code.jquery.com 1.4%
yandex.st 0.3%
ajax.aspnetcdn.com 0.2%

What are the top 300K sites doing

jQuery Hosted from, 1 Mar 13

hostname percentage 
1.4.2 (http) 1.7%
1.7.2 (http) 1.6%
1.7.1 (http) 1.6%
1.3.2 (http) 1.2%
1.7.2 (https) 1.1%
1.8.3 (http) 1.0%

What are the top 300K sites doing

jQuery Version if loading from Google, 1 Mar 13

Add Class to all p

var paragraphs = document.querySelectorAll( "p" );
var plen       = paragraphs.length;
var i          = 0;

for (i = 0; i < plen; i++ ) {
    paragraphs[ i ].classList.add('red');
};
jQuery('p').addClass('red');

jQuery

JavaScript

nojquery

By Prathik S

nojquery

  • 1,734