SlideShare a Scribd company logo
jQuery Proven

PERFORMANCE
TIPS & TRICKS                                   WITH ADDY OSMANI




IMAGES COPYRIGHT HASBRO AND TONKA, 1935-2011.                      and Mr. Monopoly
ABOUT ME
• JavaScript & UI Developer at Aol
• jQuery Core [Bugs/Docs/Learning] teams
• SocketStream Core Team Member
• Writer [Script Junkie / AddyOsmani.com/.net etc]
We used to give out these awesome
free coasters back in the 90s.
We now create real-time web
frameworks and next-gen platforms.
Enough of that..

LET’S START!
WHY DOES PERFORMANCE
MATTER?
• Apps should be snappy, not sloppy.
• Best practices offer optimal approaches
  to solving problems.
• If we don’t follow them, browsers can end
  up having to do more work.
MORE WORK =
MORE MEMORY USE =
SLOWER APPS.
TODAY, ALL OF THESE
SLIDES COME WITH
PERFORMANCE TESTS.
Not just saying X is faster...we’re proving it too.
PERFORMANCE TESTING

• jsPerf.com - a great way to easily create tests
   comparing the performance of code snippets
   across different browsers
• Makes it simple for anyone to share or modify
   tests
• Used by the jQuery project, Yahoo and many
   other dev. teams

                            Thanks to Mathias Bynens for creating it!
Example of test output
Anyone can tell what the fastest and slowest snippets are.




                                                             http://jsperf.com/jquery-tree-traversing
Quick jsPerf tips for beginners

 • ops/sec is the number of times a test is
    projected to execute in a second
 • Tests get repeatedly executed until they reach the
    minimum time required to get a percentage
    uncertainly
 • Results based on ops/sec accounting for margin
    of error. The higher ops/sec the better.
1
PERFORMANCE TIP
STAY UP TO DATE!
• Always use the latest version of jQuery
  core where possible.
• Remember to regression test your
  scripts and plugins before upgrading.
• Current version is 1.6.2 and 1.7 will
  probably get released this fall.
MOST POPULAR SITES USING JQUERY ON
THE GOOGLE CDN




                                               Old




                            Stats from Scott Mitchell
INTERESTING FACTS
• Performance improvements and new
  features usually land in major releases (eg.
  1.6/1.x)
• Bug patches and regression fixes land
  in 1.x.y releases (eg. 1.6.2)
• Plenty of reasons to upgrade!
WHY?
• Older versions won’t offer these instant
  performance benefits
• As 47% of the popular sites on the web
  use jQuery, changes are heavily tested.
• Upgrading usually a pain-free process.
Selector comparisons1.4.2 vs. 1.4.4
 vs. 1.6.2
                             1.4.2           1.4.4                   1.6.2



           $(’.elem’)



  $(’.elem’, context);



context.find(’.elem’);


                         0           27500      55000             82500                110000

                                                        http://jsperf.com/jquery-1-4-2-vs-1-6-2-comparisons
1.6.x improvements




.attr() performance improved          .val() faster in 1.6.x
http://jsperf.com/attr-vs-attrhooks   http://jsperf.com/valhooks-vs-val/2
Note
• There are certain selectors that are
  slower in 1.6.x than they are in 1.4.x
• Be aware of the performance of
  selectors you’re using and you’ll be fine
2
PERFORMANCE TIP
KNOW YOUR SELECTORS
• All selectors are not created equally
• Just because a selection can be made in
  many ways, doesn’t mean each selector
  is just as performant
• Do you know what the fastest to
  slowest selectors are?
Fast: ID & Element Selectors

$(‘#Element,  form,  input’)


• ID and element selectors are the fastest
• This is because they’re backed by native
  DOM operations (eg. getElementById()).
Slower: Class Selectors

$(‘.element’)


• getElementsByClassName() not
  supported in IE5-8
• Supported in FF3+, Safari 4+, Chrome
  4+, Opera 10.10+ so faster in these.
                                  http://www.quirksmode.org/dom/w3c_core.html
Slowest: Pseudo & Attribute
Selectors
$(‘:visible,  :hidden’);  
$(‘[attribute=value]’);

• This is due to no native calls available that we can
   take advantage of.

• querySelector() and querySelectorAll()
   help with this in modern browsers.

                                           http://www.quirksmode.org/dom/w3c_core.html
querySelectorAll()
 • Allows searching the DOM for elems based
    on a CSS selector in modern browsers.

 • jQuery attempts to use qSA without hitting
    Sizzle for queries including $(‘#parent .child’) or
    $(‘.parent a[href!=”hello”]’)

 • Optimise for selectors that use qSA vs. those
    that don’t such as :first, :last, :eq etc.
 • Valid selectors have a better chance of using it.
jsPerf selector comparison
                          1.4.2            1.6.2


              ID

           Class

 Descendent tag

      Attributes

Input/form select

       :nth-child

                    0   75000     150000    225000             300000

                                             http://jsperf.com/dh-jquery-1-4-vs-1-6/6
BUT I’M TOO PRETTY TO GO
TO JAIL!


Pseudo-selectors
are powerful..but
slow, so be careful
when using them.
The :hidden pseudo-selector
if ( jQuery.expr && jQuery.expr.filters ) {
    jQuery.expr.filters.hidden = function( elem ) {
        var width = elem.offsetWidth,
            height = elem.offsetHeight;

        return (width === 0 && height === 0) ||(!jQuery.support.reliableHiddenOffsets &&
(elem.style.display ||jQuery.css( elem, "display" )) === "none");
    };

    jQuery.expr.filters.visible = function( elem ) {
        return !jQuery.expr.filters.hidden( elem );
    };
}




   • Looking at the code, why is this bad?
Be careful because..
 • If you use this with 100 elements, jQuery
   calls it 100 times.
 • :hidden is powerful but like all pseudos
   must be run against all the elements
   in your search space.
 • If possible, avoid them!.
jsPerf performance tests
 • jQuery1.4.2 vs 1.6 selector comparison tests
     http://jsperf.com/dh-jquery-1-4-vs-1-6/6

 •   jQuery 1.2.x vs 1.4.x vs. 1.6.x vs. qSA vs. qS vs.
     other frameworks http://jsperf.com/jquery-vs-
     sizzle-vs-midori-vs-mootools-selectors-test/26
3
PERFORMANCE TIP
UNDERSTAND PARENTS
AND CHILDREN
1) $(‘.child", $parent).show(); //context

2) $parent.find(‘.child’).show(); //find()

3) $parent.children(".child’).show(); //immediate children

4) $(‘#parent > .child’).show(); //child combinator selector

5) $(‘#parent .child’).show(); //class selector

6) $('.child', $('#parent')).show(); //created context
Context
1)  $(‘.child’,  $parent).show();  




• Here the scope must be parsed and
   translated to $.parent.find(‘child’).show();
   causing it to be slower.
• ~5-10% slower than the fastest option
.find()
2)  $parent.find(‘.child’).show();  




 • This is the fastest of the entire set. I’ll
   explain why shortly.
Immediate children

3)  $parent.children(‘.child’).show();  


 • Internally uses $.sibling and JavaScript’s
   nextSibling() to find nodes following
   other nodes in the same tree.
 • ~50% slower than the fastest option
CSS child combinator selector
4)  $(‘#parent  >  .child’).show();

• Uses a child combinator selector, however
  Sizzle works from right to left.
• Bad as it will match .child before checking
  it’s a direct child of the parent.
• ~70% slower than the fastest option
CSS class selector

5)  $(‘#parent  .child’).show();  


 • Uses a class selector and is constrained by the
    same rules as 4).
 • Internally also has to translate to using .find()
 • ~77% slower than the fastest option
Created context
6)  $(‘.child’,  $(‘#parent’)).show();  




• Equivalent internally to $(‘#parent’).find(‘.child’),
   however note that parent is a jQuery object.
• ~23% slower than the fastest option
The fastest option is..
2)  $parent.find(‘.child’).show();  


 • The parent selector is already cached here, so it
    doesn’t need to be refetched from the DOM.

 • Without caching this is ~ 16% slower.
 • Directly uses native getElementById,
    getElementsByName, getElementsByTagName to
    search inside the passed context under the hood.
It’s worth noting..

 • .find() performs a recursive top-down
   search of all child and sub-elements
 • Other options presented may be more
   suitable/performant depending on what
   you’re trying to achieve.
jsPerf performance tests

 • context vs. selector vs. selector and .find()
   vs. parent/child selector vs. immediate
   children: http://jsperf.com/jquery-
   selectors-context/2
4
PERFORMANCE TIP
Don’t use jQuery unless it’s
absolutely necessary
 • Remember it’s sometimes more
   performant to use regular ol’ JavaScript
 • jQuery is JavaScript so there’s no harm.
 • How many times have you done this..
Eg. jQuery over-use of attr()

 $('a').bind(‘click’, function(){
   console.log('You clicked: ' + $(this).attr('id'));
 });


• jQuery’s ID selector only gets to
   document.getElementById after parsing
   the selector and creating a jQuery object
Why not use the DOM
element itself? This is faster:

 $('a').bind(‘click’, function(){
   console.log('You clicked: ' + this.id);
 });


• Avoid the overhead by remembering the
  jQuery-way isn’t always the best way.
Quick note:
 • this.id and $(this).attr(‘id’) both return the
   same value but remember..
   • At a lower-level, this.getAttribute(‘id’) is
     equivalent to $(this).attr(‘id’);
   • However, as the attribute stays up to
     date, this.id is still better to use.
jsPerf Performance tests
 • $(this).attr(‘id’) vs. this.id http://jsperf.com/
   el-attr-id-vs-el-id/2
 • Using the former is actually 80-95%
   slower than directly accessing the
   attribute through the DOM element.
5
PERFORMANCE TIP
CACHING IS YOUR FRIEND.
var parents =  $(‘.parents’), //caching

    children = $(‘.parents’).find(‘.child’), //bad

    kids = parents.find(‘.child’); //good


 • Caching just means we’re storing the
   result of a selection for later re-use.
So remember..

• Each $(‘.elem’) will re-run your search
  of the DOM and return a new collection
• You can then do anything with the cached
  collection.
• Caching will decrease repeat selections.
Doing just about anything with the
cached collection.

var foo = $(‘.item’).bind('click', function({ 
                                              
     foo.not(this).addClass(‘bar’)
                  .removeClass(‘foobar’)
                  .fadeOut(500);
});
jsPerf performance tests

 • Comparing the performance of cached
   selectors vs. repeated element selections
   http://jsperf.com/ns-jq-cached
 • Uncached selectors in these tests are
   anywhere up to 62% slower than their
   cached equivalents.
6
PERFORMANCE TIP
CHAINING
var parents =  $(‘.parents’).doSomething().doSomethingElse();


 • Almost all jQuery methods return a jQuery
    object and support chaining.
 • This means after executing a method on a
    selection, you can continue executing more.
 • Less code and it’s easier to write!
No-chaining vs. chaining
//Without  chaining
$(‘#notification’).fadeIn(‘slow’);
$(‘#notification’).addClass(‘.activeNotification’);
$(‘#notification’).css(‘marginLeft’,  ‘50px’);

//With  chaining
$(‘#notification’).fadeIn(‘slow’)
                                    .addClass(‘.activeNotification’)      
                                    .css(‘marginLeft’,  ‘50px’);
jsPerf performance tests


 • Chained calls vs. separate calls vs. cached
   separate calls http://jsperf.com/jquery-chaining
 • Chaining is the fastest followed by cached
   separate calls.
7
PERFORMANCE TIP
EVENT DELEGATION
• The idea that you allow events to bubble
  up the DOM tree to a parent element.
• Important as it allows you to only bind a
  single event handler rather than 100s.
• Works with elements in the DOM at
  runtime (and those injected later)
.bind()
 • Allows you to attach a handler to an event
   such as ‘click’, ‘mouseenter’ etc for elements
 • With larger sets, the browser has to keep
   track of all event handlers and this can take
   time to bind.
 • Doesn’t work with dynamically inserted
   elements.
.live()
 • Simplest form of supported event delegation
 • Allows you to attach a handler to an event for
   current and future matches of a selector

 • Works best for simple scenarios but has
   flaws (has to be at the top of the chain, fails
   alongside traversals)

 • Can’t chain to it, unlike other jQuery
   methods.
.delegate()
 • Allows you to specify the particular DOM
   element would like to bind to when attaching
   handlers to selections that match current/future
   elems.

 • Ensures we don’t bubble all the way up the DOM
   to capture an element’s target (unlike .live())

 • Use when binding the same event handler to
   multiple elements
jsPerf performance tests
 • .live() vs .delegate() vs. delegate from body variations
    http://jsperf.com/jquery-delegate-vs-live-table-test/2

 • .bind() vs .click() vs. live() vs. delegate() http://
    jsperf.com/bind-vs-click/12

 • .live() vs .live() context vs .delegate() vs. delegating to
    document.body http://jsperf.com/jquery-live-vs-
    jquery-delegate/15
8
PERFORMANCE TIP
THE DOM ISN’T A DATABASE

• jQuery allows you to treat it like one but it isn’t.
• Remember each DOM insertion is costly.
• This means keep the use of .append
   (), .insertBefore(), .insertAfter() etc. to a
   minimum.
It’s also important to remember

 • Traversing the DOM to retrieve content or
   information stored in .text(), .html() etc is not
   the most optimal approach.

 • This could be in .data() instead, which allows us
   to attach any type of data to DOM elements
   safely.
Tip 1: Better .append() usage

 • Minimise use by building HTML strings in-
   memory and using a single .append()
   instead.
 • Multiple appends can be up to 90%
   slower when not appending to cached
   selectors and up to 20% slower with them.
Tip 2: Use .detach()

 • Works great when you’re doing heavy
   interaction with a node
 • Allows you to re-insert the node to the
   DOM once you’re ready
 • Up to 60% faster than working with
   undetached nodes.
.detach() example
$(‘p’).click(function(){
      $(this).toggleClass(‘off’);
});

var p;
$(‘button’).click(function(){
      if ( p ) {
        /*..additional modification*/
        p.appendTo(‘body’);
        p = null;
      } else {
        p = $(‘p’).detach();
      }
});
Tip 3: Better .data() usage

 • We usually attach data like this..
   $(‘#elem’).data(  key  ,  value  );


 • But this is actually much faster..
    $.data(‘#elem’,  key  ,  value);


 • as there’s overhead creating a jQuery
    object and doing data-parsing in the first.
Notes

 • Although $.data is faster, it cannot be
   passed a selector, only a node.
 • This means $.data(elem, key, value) works
   where elem is already defined as an
   element.
jsPerf performance tests
 • .detach() vs not detaching http://
   jsperf.com/to-detach-or-not-to-detach
 • jQuery.data vs jQuery.fn.data: http://
   jsperf.com/jquery-data-vs-jqueryselection-
   data/11
 • Multiple appends vs a single append http://
   jsperf.com/string-concat-single-append-vs-
   multiple-append
9
PERFORMANCE TIP
UNDERSTAND LOOPS

• Did you know that native for and while loops are
   faster than using $.each() and $.fn.each()?
• jQuery makes it easy to iterate over collections,
   but remember it’s not always the most
   performant option.
• Plugins like Ben Alman’s $.each2() sometimes
   perform better than $.fn.each
AVOID LOOPS IF YOU CAN. HARD, BUT
NESTED DOM SELECTORS MAY PERFORM
BETTER.
 • Unless absolutely necessary, avoid loops. They’re
    slow in every programming language.
 • If possible, use the selector engine instead to
    access the elements needed.
 • There are of course places loops cannot be
    substituted but try your best to optimise.
That said..
 • Developers often need to iterate
 • The closure-scope provided by $.each is usually
    required for other reasons.
 • Should loops be such a pain-point you need to
    unroll them you’re lucky, but remember there
    are alternatives possible.
jsPerf performance tests
 • jQuery.each vs. for, while, reverse for,
    jQuery.fn.each and other loop approaches: http://
    jsperf.com/jquery-each-vs-for-loop/24
 • jQuery.fn.each vs Ben Alman’s .each2() http://
    jsperf.com/jquery-each-vs-quickeach/3
PERFORMANCE TIP




10
Avoid constructing new jQuery objects unless
necessary

$(‘a’).map(function(){ return $(this).text();});


 • Developers commonly create new jQuery
   objects on iterations such as the above just to
   access some text
 • Using a lower-level method like $.method()
   rather than $.fn.method() can help improve
   performance with this.
                                     Thanks to James Padolsey for this tip
$.text vs $.fn.text




                      http://jsperf.com/jquery-text-vs-html/5
Notes:
 • Not all jQuery methods have their own single-
    node functions
 • James proposed jQuery.single() as a solution to
    this problem
 • It uses a single jQuery object for all calls to
    jQuery.single() and only works for single DOM
    elements.


                                       http://james.padolsey.com/javascript/76-bytes-for-faster-jquery/
Bonus Tip
KEEP YOUR CODE DRY

• Repeating the same code increases the size of
  your code-base and reduces productivity

• DRY (don’t repeat yourself) encourages one
  representation of each piece of knowledge

• Keeping code minimal can also remind you
  that chaining, caching etc can assist with this.
Let’s go through a quick example..


/*Let's store some default values to be read later*/
var defaultSettings = {};
defaultSettings['carModel']   = 'Mercedes';
defaultSettings['carYear’]    = 2012;
defaultSettings['carMiles']   = 5000;
defaultSettings['carTint']    = 'Metallic Blue';
 
Non-DRY code
$('.someCheckbox').click(function(){
   if ( this.checked ){                
        $('#input_carModel').val(defaultSettings.carModel);
        $('#input_carYear').val(defaultSettings.carYear);
        $('#input_carMiles').val(defaultSettings.carMiles);
        $('#input_carTint').val(defaultSettings.carTint);
 
 } else {         
        $('#input_carModel').val('');     
        $('#input_carYear').val('');
        $('#input_carMiles').val('');
        $('#input_carTint').val('');
 }
});
DRY code
var props = ['carModel', 'carYear', 'carMiles', 'carTint'];

$('.someCheckbox').click(function(){        
    var checked = this.checked;
    /*
        What are we repeating?
        1. input_ precedes each field name
        2. accessing the same array for settings
        3. repeating value resets
  
        What can we do?
        1. programmatically generate the field names
        2. access array by key
        3. merge this call using terse coding (ie. if checked,
            set a value, otherwise don't)
    */  
       $.each(props,function(i,key){
               $('#input_' + key).val(checked ? defaultSettings[key] : '');
       });
});
THANKS.

• Props to Adam Sontag, JD Dalton, Paul Irish,
  Timmy Willison, James Padolsey, Mathias
  Bynens, Matt Baker and the team @jquery
• For more on me:
 • http://addyosmani.com
 • @addyosmani
THAT’S IT!
GO BUILD AWESOME THINGS.

More Related Content

Viewers also liked (20)

jQuery Essentials by Marc Grabanski, has 115 slides with 174071 views.The document discusses jQuery and its uses and methods. It introduces jQuery as a way to write JavaScript code that works across browsers. It provides examples of how jQuery can be used to select and manipulate HTML elements using simpler syntax compared to vanilla JavaScript. Key jQuery methods are also summarized, including how to select elements, modify attributes, handle events, add/move elements, and perform animations and AJAX requests.
jQuery EssentialsjQuery Essentials
jQuery Essentials
Marc Grabanski
115 slides174.1K views
jQuery in 15 minutes by Simon Willison, has 14 slides with 41544 views.This document provides an overview of jQuery, a JavaScript library for DOM manipulation. It discusses jQuery's CSS selector syntax, methods for manipulating DOM elements and collections, event handling, AJAX support through methods like load() and get(), and how jQuery is extensible through plugins. The document also provides examples of DOM traversal, value retrieval, event binding, and chaining methods.
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
Simon Willison
14 slides41.5K views
jQuery Performance Tips and Tricks (2011) by Addy Osmani, has 20 slides with 5123 views.Today we’re going to take a look at best practices, tips and tricks for improving the performance of your jQuery code. Performance optimization is a crucial aspect of building ‘snappy’ client-side applications and something which all developers using jQuery should bare in mind.
jQuery Performance Tips and Tricks (2011)jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)
Addy Osmani
20 slides5.1K views
jQuery for beginners by Arulmurugan Rajaraman, has 22 slides with 35855 views.Slides for presentation C002 | jQuery for beginners in Sumofyou Technologies
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
22 slides35.9K views
Performance management system by tsheten, has 22 slides with 129638 views.The document discusses performance management systems (PMS), which provide a structured approach to communicate business strategy, establish performance expectations, facilitate management, and measure and motivate performance. A key part of PMS is setting employee performance expectations, maintaining ongoing performance dialogue, and conducting annual performance appraisals. PMS also includes procedures for addressing underperformance, encouraging development, training managers, and resolving disputes. The goals of PMS are to guide employee efforts, assess individuals, teams, and the organization, and inform decisions around promotions, pay, and training needs.
Performance management systemPerformance management system
Performance management system
tsheten
22 slides129.6K views
The Top 5 Performance Management Tools by Bernard Marr, has 12 slides with 160760 views.Summary of a report that looked at the state-of-the-art in performance management. It identifies the top 5 tools used today to manage performance and adds some words of advice.
The Top 5 Performance Management ToolsThe Top 5 Performance Management Tools
The Top 5 Performance Management Tools
Bernard Marr
12 slides160.8K views
Developing Metrics and KPI (Key Performance Indicators by Victor Holman, has 38 slides with 95223 views.Get a FREE performance management kit and access to all of Victor's full videos at: www.lifecycle-performance-pros.com This presentation covers the basics of developing successful performance metrics, from developing winning KPIs, learning how to develop the right metrics, the rules of developing KPIs and metrics and common performance metrics for managing a successful organization.
Developing Metrics and KPI (Key Performance IndicatorsDeveloping Metrics and KPI (Key Performance Indicators
Developing Metrics and KPI (Key Performance Indicators
Victor Holman
38 slides95.2K views
Performance Management System by Surabhi Mohan, has 31 slides with 126394 views.This document outlines the key aspects of a performance management system, including: 1. The meaning, scope, and objectives of performance management, which aims to enhance employee performance and provide feedback. 2. A four-phase performance management cycle of setting expectations, maintaining dialogue, evaluation, and addressing poor performance. 3. Prerequisites for an effective performance management system including clear policies and procedures. 4. Factors to consider when seeking to improve employee performance through targets and other drivers.
Performance Management SystemPerformance Management System
Performance Management System
Surabhi Mohan
31 slides126.4K views
jQuery vs AJAX Control Toolkit by Erik Ralston, has 14 slides with 4853 views.A short discussion of the difference in purpose between AJAX Control Toolkit and jQuery and when one should be used over the other.
jQuery vs AJAX Control ToolkitjQuery vs AJAX Control Toolkit
jQuery vs AJAX Control Toolkit
Erik Ralston
14 slides4.9K views
Go to hell Flash, we don't need you anymore! GothamJs by michalbu, has 98 slides with 1680 views.When back in 1996 Macromedia introduced Flash, no one suspected that this plugin will revolutionize the world of the Internet and move an open, Web-based technologies into the background. Today, after more than 15 years, situation slowly reverses - finally creating interactive websites, games or advertisements is possible without using any browser plugins. But is it enough? Michal will take us on a tour of the world's holy war between Plugins like Flash and HTML, and will attempt to answer this question, preseting poorly known HTML5 features, services and open source tools he is working on now (like http://bly.sk).
Go to hell Flash, we don't need you anymore! GothamJsGo to hell Flash, we don't need you anymore! GothamJs
Go to hell Flash, we don't need you anymore! GothamJs
michalbu
98 slides1.7K views
DISCUS: Distributed Innovation and Scalable Collaboration in Uncertain Settings by Xavier Llorà, has 11 slides with 1010 views.DISCUS: Distributed Innovation and Scalable Collaboration in Uncertain Settings
DISCUS: Distributed Innovation and Scalable Collaboration in Uncertain SettingsDISCUS: Distributed Innovation and Scalable Collaboration in Uncertain Settings
DISCUS: Distributed Innovation and Scalable Collaboration in Uncertain Settings
Xavier Llorà
11 slides1K views
서블릿(servlet) by JungHoon Lee, has 7 slides with 12040 views.1. 서블릿이란? 2. JSP와 서블릿의 차이점 3. 서블릿 컨테이너(Tomcat) 4. 서블릿의 동작과정 5. 배포기술자(web.xml) 6. 서블릿 파일의 경로
서블릿(servlet)서블릿(servlet)
서블릿(servlet)
JungHoon Lee
7 slides12K views
Open-source Mic Talks at AOL by Addy Osmani, has 17 slides with 4368 views.This document discusses the speaker's involvement with the jQuery open source project. It provides background on jQuery, describing it as a JavaScript library that simplifies DOM manipulation. It then outlines the speaker's various roles contributing to jQuery, including core bug triage, API documentation, and evangelism. Challenges of contributing to open source projects from work and managing time zones are discussed. Overall, the document encourages getting involved in open source and notes that significant contributions can be made even without large time commitments.
Open-source Mic Talks at AOLOpen-source Mic Talks at AOL
Open-source Mic Talks at AOL
Addy Osmani
17 slides4.4K views
Prototype & jQuery by Remy Sharp, has 25 slides with 37036 views.A walk through process comparison between Prototype and jQuery to help developers go from one language to another.
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
Remy Sharp
25 slides37K views
Client-Side Packages by Domenic Denicola, has 37 slides with 14180 views.This document discusses client-side JavaScript packages and module systems. It begins by describing CommonJS and AMD module systems, noting problems with AMD including configuration complexity and inability to easily consume third-party code. It then introduces the concept of packages as a better unit of code reuse than modules alone. NPM is presented as a package manager that solves problems of downloading, installing dependencies, and accessing other packages' code. Key aspects of NPM packages like directory structure and package.json are outlined. The document concludes by briefly covering NPM features like dependency hierarchies, Git dependencies, and using NPM without publishing to the public registry.
Client-Side PackagesClient-Side Packages
Client-Side Packages
Domenic Denicola
37 slides14.2K views
Servlet/JSP course chapter 1: Introduction to servlets by JavaEE Trainers, has 18 slides with 3476 views.This document provides an overview of servlets and Java web development. It discusses what servlets are, the servlet lifecycle including initialization, service and destruction methods. It also covers retrieving request parameters, generating responses, and an example of using servlet lifecycle methods. The document includes an exercise to build a basic servlet application that adds users to an email list.
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
JavaEE Trainers
18 slides3.5K views
jQuery Anti-Patterns for Performance & Compression by Paul Irish, has 68 slides with 25260 views.The document discusses various jQuery anti-patterns that can negatively impact performance and compression. It describes caching selections, using document fragments to append content outside of loops, avoiding unnecessary re-querying of elements, and leveraging event delegation with delegate() instead of binding individual handlers. The document emphasizes optimizing selector syntax from right to left, avoiding universal selectors, and detaching elements from the DOM when manipulating them to improve speed.
jQuery Anti-Patterns for Performance & CompressionjQuery Anti-Patterns for Performance & Compression
jQuery Anti-Patterns for Performance & Compression
Paul Irish
68 slides25.3K views
Using Objects to Organize your jQuery Code by Rebecca Murphey, has 23 slides with 20573 views.When you move beyond simple snippets of jQuery and start developing more complex interactions, your code can quickly become unwieldy and difficult to debug and maintain. In this presentation, I outline an object-based approach to organizing your jQuery.
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery Code
Rebecca Murphey
23 slides20.6K views
forensic document examiner using graphology science by Gargee Hiray, has 42 slides with 760 views.The document describes a project to develop a system called FODEX (Forensics Document Examiner) that examines documents and generates an algorithmic analysis of human handwriting. It will work by comparing different handwriting samples using image processing algorithms. The system will preprocess images, perform thinning, segmentation, feature extraction and profile generation to analyze handwriting traits defined in graphology and generate a personalized profile or report for the user. It aims to provide an automated, user-friendly and accurate alternative to existing handwriting analysis systems. The project plan outlines the implementation progress and technical details like using Java and libraries for image processing, MySQL database, and UML diagrams.
forensic document examiner using graphology scienceforensic document examiner using graphology science
forensic document examiner using graphology science
Gargee Hiray
42 slides760 views

Similar to jQuery Proven Performance Tips & Tricks (20)

How to use selenium successfully by TEST Huddle, has 111 slides with 1964 views.In this webinar, Dave Haeffner (Elemental Selenium, USA) discusses how to: - Build an integrated feedback loop to automate test runs and find issues fast - Setup your own infrastructure or connect to a cloud provider -Dramatically improve test times with parallelization https://huddle.eurostarsoftwaretesting.com/resource/webinar/use-selenium-successfully/
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfully
TEST Huddle
111 slides2K views
Mastering Test Automation: How to Use Selenium Successfully by Applitools, has 90 slides with 4808 views.** WATCH FULL WEBINAR RECORDING HERE: https://youtu.be/06H-6hjyyvI ** What is Selenium? Why should you use it? And how do you use it successfully? In this webinar, Automation expert Dave Haeffner answers these questions as he steps through the why, how, and what of Selenium. Dave also discusses how to start from nothing and build out a well factored, maintainable, resilient, fast and scalable set of tests. These tests will not only work well, but across all of the browsers you care about, while exercising relevant functionality that matters to your business. Watch this webinar and learn how to: * Decompose an existing web application to identify what to test * Pick the best language for you and your team * Write maintainable and reusable Selenium tests that will be cross-browser compatible and performant * Dramatically improve your test coverage with automated visual testing * Build an integrated feedback loop to automate test runs and find issues fast
Mastering Test Automation: How to Use Selenium Successfully Mastering Test Automation: How to Use Selenium Successfully
Mastering Test Automation: How to Use Selenium Successfully
Applitools
90 slides4.8K views
jQuery Performance Tips and Tricks by Valerii Iatsko, has 14 slides with 298 views.This document provides tips for improving jQuery performance, including using the latest jQuery version, caching selectors, avoiding unnecessary DOM touches, building HTML strings before appending to DOM, preferring group queries over loops, and checking for element existence before manipulating. It also recommends the fastest and slowest selector types, and reviewing the jQuery source code for understanding.
jQuery Performance Tips and TricksjQuery Performance Tips and Tricks
jQuery Performance Tips and Tricks
Valerii Iatsko
14 slides298 views
The Many Ways to Test Your React App by All Things Open, has 96 slides with 2147 views.Van Wilson Senior Consultant with Cardinal Solutions Find more by Van Wilson: https://speakerdeck.com/vjwilson All Things Open October 26-27, 2016 Raleigh, North Carolina
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
All Things Open
96 slides2.1K views
full-stack-webapp-testing-with-selenium-and-rails.pdf by Brian Takita, has 37 slides with 5 views.• Want to test your entire Web 2.0 app, from AJAX and DHTML through browser-rendered HTML into a live instance of your application and database? Most web testing frameworks have gaps in their coverage: JUnit and Test::Unit miss the client frontend; JSUnit misses the server backend; web testing frameworks miss some or all of the JavaScript. With Selenium we have a framework that can test the whole application, from browser-executed JavaScript, through a live application backend, then back to assertions on browser-rendered DOM code. Selenium RC takes this further: since you write your tests in your application language, your tests can do data setup and assertions based directly on server-side domain objects that may be inaccessible or only partially accessible from the client side. On our teams we have used and developed a series of helper methods and assertions that allow testing of AJAX and DHTML functions as well.
full-stack-webapp-testing-with-selenium-and-rails.pdffull-stack-webapp-testing-with-selenium-and-rails.pdf
full-stack-webapp-testing-with-selenium-and-rails.pdf
Brian Takita
37 slides5 views
Enterprise Strength Mobile JavaScript by Troy Miles, has 46 slides with 11042 views.JavaScript has a well deserved reputation of be hard to write and debug. Put it on a mobile device and the problems increase exponentially. Mobile browsers lack all of the niceties that developers rely on to do testing and debugging including the most fundamental tool, the debugger. But it is possible to write quality JavaScript on a mobile device without relying on blind luck. In this talk I will show all of the tools and tricks that I learned in my 12 month development of the new KBB.com mobile site.
Enterprise Strength Mobile JavaScriptEnterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScript
Troy Miles
46 slides11K views
33rd degree by Dariusz Kordonski, has 191 slides with 354 views.The document discusses challenges faced with automated testing at scale for a large codebase with many dependencies, technologies, and test types. It describes how the large number of tests led to slow build times, failures blocking changes, and reduced developer productivity. Specific issues mentioned include monolithic test organization, slow unit/functional tests, non-deterministic races/timeouts, and re-running all tests on every commit. The document advocates for strategies like separating test types, running in parallel, and using page objects to isolate tests from UI changes.
33rd degree33rd degree
33rd degree
Dariusz Kordonski
191 slides354 views
Testing Ext JS and Sencha Touch by Mats Bryntse, has 67 slides with 8361 views.- Testing JavaScript code helps ensure quality and allows for refactoring and code handovers. Unit, integration, and functional testing methodologies were discussed. - Siesta was introduced as a JavaScript testing tool that supports unit and functional testing for Ext JS and Sencha Touch. It allows simulating user interactions and verifying results. - Writing testable code through separation of concerns, avoiding direct DOM manipulation, and supporting dependency injection were recommended to facilitate automated testing. Continuous integration was also recommended for running tests regularly.
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
Mats Bryntse
67 slides8.4K views
Getting Started with Selenium by Dave Haeffner, has 115 slides with 1988 views.The document provides an overview of getting started with Selenium and outlines 8 steps to write automated tests: 1. Define a test strategy by determining what to test and which browsers to support 2. Choose a programming language like Java and set up dependencies 3. Learn Selenium fundamentals like locating elements and common actions 4. Write a first test to log in to a sample site 5. Create page objects and a base page to make tests reusable and maintainable 6. Add waits to make tests more resilient when waiting for elements 7. Set up a test harness for centralized setup/teardown, reporting and parallelization 8. Add cross-browser testing by using browser drivers locally or remotely
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
Dave Haeffner
115 slides2K views
How To Use Selenium Successfully by Dave Haeffner, has 84 slides with 1187 views.This document provides a 10 step guide to using Selenium successfully. It begins by defining a test strategy and choosing a programming language. It then covers Selenium fundamentals like locators and common actions. Steps include writing the first test, implementing page objects, making tests resilient with waits, and adding cross-browser execution. The guide also discusses test frameworks, continuous integration, and finding additional information. The overall goal is to write reusable, maintainable tests that run across browsers to provide automated feedback and catch issues early.
How To Use Selenium SuccessfullyHow To Use Selenium Successfully
How To Use Selenium Successfully
Dave Haeffner
84 slides1.2K views
Browser Automated Testing Frameworks - Nightwatch.js by Luís Bastião Silva, has 20 slides with 7043 views.Browser automation testing frameworks like Nightwatch.js allow developers to automatically test their web applications. Nightwatch.js provides an easy way to write tests using JavaScript. Tests can launch browsers, fill forms, click links, and verify outputs. Nightwatch.js tests can help developers catch errors that might break functionality and ensure compatibility across browsers. The documentation is good and it is actively maintained with over 10,000 downloads per month. Developers can integrate Nightwatch.js tests into their own projects to avoid future issues.
Browser Automated Testing Frameworks - Nightwatch.jsBrowser Automated Testing Frameworks - Nightwatch.js
Browser Automated Testing Frameworks - Nightwatch.js
Luís Bastião Silva
20 slides7K views
How To Use Selenium Successfully (Java Edition) by Sauce Labs, has 83 slides with 7751 views.Dave Haeffner, a Selenium expert and active member of the Selenium project, steps through the why, how, and what of Selenium (the open-source automated web-testing tool for functional testing). He also discusses how to start from nothing and build out a well-factored, maintainable, resilient, fast and scalable set of tests in Java. These will test your app across all of the browsers you care about, while exercising relevant functionality that matters to your business.
How To Use Selenium Successfully (Java Edition)How To Use Selenium Successfully (Java Edition)
How To Use Selenium Successfully (Java Edition)
Sauce Labs
83 slides7.8K views
Selenium testing - Handle Elements in WebDriver by Vibrant Technologies & Computers, has 38 slides with 288 views.This presentation is about the following points, 1. Handle Browser, 2. Handle Edit box / Text Box, 3. Handle Link Element, 4. Handle Button, 5. Handle Text Area / Message, 6. Handle Dropdown box /List box, 7. Handle Radio Button, 8. Handle Check Box
Selenium testing - Handle Elements in WebDriver Selenium testing - Handle Elements in WebDriver
Selenium testing - Handle Elements in WebDriver
Vibrant Technologies & Computers
38 slides288 views
URUG Ruby on Rails Workshop - Sesssion 5 by jakemallory, has 21 slides with 525 views.This document provides an overview and instructions for a Ruby on Rails workshop. It introduces the presenter and discusses Rails frameworks. It then covers topics like data handling, using Git and the server log, named scopes, click-to-sort columns, and search functionality. Code examples and implementation hints are provided for tasks like adding sort order icons, search forms, and search result filtering.
URUG Ruby on Rails Workshop - Sesssion 5URUG Ruby on Rails Workshop - Sesssion 5
URUG Ruby on Rails Workshop - Sesssion 5
jakemallory
21 slides525 views
Java script unit testing by Mats Bryntse, has 64 slides with 3016 views.This document discusses the importance of unit testing JavaScript code. It provides reasons for testing JavaScript, such as avoiding bugs when refactoring code or introducing errors. The document discusses how to write testable JavaScript by separating business logic from views. It also recommends choosing JavaScript unit testing tools like Jasmine and Siesta, and integrating tests into continuous integration processes to run automatically on commits. Functional testing tools like Selenium are also mentioned for testing user interactions across browsers.
Java script unit testingJava script unit testing
Java script unit testing
Mats Bryntse
64 slides3K views
Migration strategies 4 by Wenhua Wang, has 23 slides with 390 views.These slides would share our experiences in reusing the legacy automation testing code (Selenium+xpath) in IE. To reuse our legacy code in IE, we explored three techinques, i.e., CSS selectors, jQuery selectors, Javascript-xpath library. These slides would discuss each technique and explain how we addressed the limitations of existing teachniques. The discussions would present how to rejuvenate the legacy code at code level and library level. Finally, the best practices would be summarized based on the practical experiences.
Migration strategies 4Migration strategies 4
Migration strategies 4
Wenhua Wang
23 slides390 views
Escaping Test Hell - ACCU 2014 by Wojciech Seliga, has 97 slides with 4031 views.My talk delivered on 10th of April 2014 in Bristol at ACCU Conference. This is the combination of a few talks I delivered over 2012 and 2013 with some latest updates. This is an experience report based on the work of many developers from Atlassian and Spartez working for years on Atlassian JIRA. If you have (or going to have) thousands of automated tests and you are interested how it may impact you, this presentation is for you.
Escaping Test Hell - ACCU 2014Escaping Test Hell - ACCU 2014
Escaping Test Hell - ACCU 2014
Wojciech Seliga
97 slides4K views
JavaScript Performance Patterns by Stoyan Stefanov, has 79 slides with 4891 views.JavaScript performance patterns focuses on optimizing JavaScript loading and execution for better performance. Some key points include reducing the number of script files, leveraging caching, minification and compression. Asynchronous loading helps prevent blocking. DOM operations are expensive so it's important to cache references, batch operations and avoid reflows. Data attributes provide a convenient way to store data on elements. Shims and polyfills should be used judiciously, loading conditionally where native support is limited. Benchmarking is crucial to identify real bottlenecks and measure impact of optimizations.
JavaScript Performance PatternsJavaScript Performance Patterns
JavaScript Performance Patterns
Stoyan Stefanov
79 slides4.9K views
Selenium Tips & Tricks - StarWest 2015 by Andrew Krug, has 82 slides with 1547 views.This document provides an overview of Selenium testing tools and techniques. It discusses headless testing using Xvfb and PhantomJS. It also covers visual testing with Applitools, using proxy servers like BrowserMob for status codes and performance testing, and emulating mobile devices. Additional topics include growl notifications, file handling, A/B testing, and resources for learning more about Selenium.
Selenium Tips & Tricks - StarWest 2015Selenium Tips & Tricks - StarWest 2015
Selenium Tips & Tricks - StarWest 2015
Andrew Krug
82 slides1.5K views
Holistic JavaScript Performance by jeresig, has 37 slides with 3973 views.This document discusses holistic performance analysis and optimization in JavaScript. It emphasizes the importance of proving performance changes with benchmarks, considering the full browser stack and real-world use cases, maintaining clean code, prioritizing cross-browser compatibility, and clearly communicating results. Key tools mentioned include JSPerf for benchmarking, BrowserScope for hosting performance data, and Google Code Search for understanding real-world usage of APIs. The document advocates optimizing against past performance rather than competitors.
Holistic JavaScript PerformanceHolistic JavaScript Performance
Holistic JavaScript Performance
jeresig
37 slides4K views

Recently uploaded (20)

Digital Nepal Framework 2.0: A Step Towards a Digitally Empowered Nepal by ICT Frame Magazine Pvt. Ltd., has 60 slides with 96 views.Digital Nepal Framework 2.0: A Step Towards a Digitally Empowered Nepal
Digital Nepal Framework 2.0: A Step Towards a Digitally Empowered NepalDigital Nepal Framework 2.0: A Step Towards a Digitally Empowered Nepal
Digital Nepal Framework 2.0: A Step Towards a Digitally Empowered Nepal
ICT Frame Magazine Pvt. Ltd.
60 slides96 views
Presentation Session 2 -Context Grounding.pdf by Mukesh Kala, has 22 slides with 142 views.This series is your gateway to understanding the WHY, HOW, and WHAT of this revolutionary technology. Over six interesting sessions, we will learn about the amazing power of agentic automation. We will give you the information and skills you need to succeed in this new era.
Presentation Session 2 -Context Grounding.pdfPresentation Session 2 -Context Grounding.pdf
Presentation Session 2 -Context Grounding.pdf
Mukesh Kala
22 slides142 views
Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ... by All Things Open, has 32 slides with 22 views.Presented at All Things Open AI 2025 Presented by Shivay Lamba - Couchbase Title: ​​Fine-Tuning Large Language Models with Declarative ML Orchestration Abstract: Large Language Models used in tools like ChatGPT are everywhere; however, only a few organisations with massive computing resources are capable of training such large models. While eager to fine-tune these models for specific applications, the broader ML community often grapples with significant infrastructure challenges. In the session, the audience will understand how open-source ML tooling like Flyte (a Linux Foundation open-source orchestration platform) can be used to provide a declarative specification for the infrastructure required for a wide array of ML workloads, including the fine-tuning of LLMs, even with limited resources. Thus the attendee will learn how to leverage open-source ML toolings like Flyte's capabilities to streamline their ML workflows, overcome infrastructure constraints, reduce cost and unlock the full potential of LLMs in their specific use case. Thus making it easier for a larger audience to leverage and train LLMs. Find more info about All Things Open: On the web: https://www.allthingsopen.org/ Twitter: https://twitter.com/AllThingsOpen LinkedIn: https://www.linkedin.com/company/all-things-open/ Instagram: https://www.instagram.com/allthingsopen/ Facebook: https://www.facebook.com/AllThingsOpen Mastodon: https://mastodon.social/@allthingsopen Threads: https://www.threads.net/@allthingsopen Bluesky: https://bsky.app/profile/allthingsopen.bsky.social 2025 conference: https://2025.allthingsopen.org/
Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ...Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ...
Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ...
All Things Open
32 slides22 views
SAP Business Data Cloud: Was die neue SAP-Lösung für Unternehmen und ihre Dat... by IBsolution GmbH, has 24 slides with 20 views.Inhalt: Daten spielen für jede Business-Transformation eine entscheidende Rolle. Mithilfe der SAP Business Data Cloud (BDC) sind Unternehmen in der Lage, sämtliche Daten miteinander zu verbinden und zu harmonisieren. Die SAP BDC stellt eine Weiterentwicklung der bisherigen SAP-Datenstrategie dar - mit SAP Datasphere und der SAP Analytics Cloud (SAC) als elementaren Säulen. Besonders hervorzuheben: Databricks ist als OEM-Produkt in die Architektur integriert. Die SAP BDC kombiniert neue und bestehende Technologien, um Anwendern angereicherte Datenprodukte, fortschrittliche Analyse-Funktionalitäten und KI-gestützte Insights-Anwendungen bereitzustellen. Kurz gesagt: Mit SAP BDC schaffen Unternehmen eine zentrale Drehscheibe für ihre geschäftskritischen Daten und legen die Basis für SAP Business AI. In unserem Expertengespräch erläutern Stefan Hoffmann (Head of Cross Solution Management SAP HANA & Analytics bei SAP) und Martin Eissing (Projektmanager bei IBsolution), was es mit der SAP Business Data Cloud genau auf sich hat und welche konkreten Vorteile mit dem neuen Angebot einhergehen. Außerdem zeigen sie auf, wie das erste Feedback der Kunden zur SAP BDC ausfällt und welche Wege Unternehmen zur SAP BDC führen. Zielgruppe: - IT-Leiter/IT-Entscheider - Data Analysts - Datenarchitekten - BI-Spezialisten - Anwender in den Fachbereichen Agenda: 1. Was ist die SAP Business Data Cloud (BDC)? 2. Einordnung in die SAP-Datenstrategie 3. Voraussetzungen und Mehrwerte der SAP BDC 4. Architektur der SAP BDC 5. Handlungsempfehlungen für SAP BW-Kunden und SAP Datasphere-Kunden 6. Q&A
SAP Business Data Cloud: Was die neue SAP-Lösung für Unternehmen und ihre Dat...SAP Business Data Cloud: Was die neue SAP-Lösung für Unternehmen und ihre Dat...
SAP Business Data Cloud: Was die neue SAP-Lösung für Unternehmen und ihre Dat...
IBsolution GmbH
24 slides20 views
Safer’s Picks: The 6 FME Transformers You Didn’t Know You Needed by Safe Software, has 56 slides with 226 views.With over 500 transformers in FME, it’s easy to stick to your favourites – but what about the hidden gems that could help you achieve more than you thought possible in your workspaces? In this lightning talk-style webinar, our Safe team panel of FME Experts will highlight underutilized transformers and clever techniques that can make your workflows more powerful, efficient, and dynamic. Whether it’s a transformer you’ve never explored before or an unexpected way to use an old favourite, you’re sure to walk away with new ideas to enhance your FME skills. Transformers they’ll cover include: Donal, the MapnikRasterizer: Learn how to generate high-quality raster outputs from vector data with precise control over symbolization and labelling Crystal, the SchemaScanner: Detect schema drift on the fly and dynamically set your output schema based on incoming data. Mark, the ModuloCounter: Discover how to group features efficiently using the number of groups, rather than group size. Evie, the Aggregator: See how versatile it can be for concatenating, listing, and joining data as an alternative to other transformers. Natalie, the RasterExpressionEvaluator: Simplify raster expressions using presets to make them repeatable and easy to manage. Dave, the ChangeDetector: Fine-tune output configurations to pinpoint exactly what’s changed in your data. Join us for this fast-paced, insight-packed session and uncover the FME transformers you didn’t know you needed!
Safer’s Picks: The 6 FME Transformers You Didn’t Know You NeededSafer’s Picks: The 6 FME Transformers You Didn’t Know You Needed
Safer’s Picks: The 6 FME Transformers You Didn’t Know You Needed
Safe Software
56 slides226 views
Dev Dives: Unleash the power of macOS Automation with UiPath by UiPathCommunity, has 16 slides with 110 views.Join us on March 27 to be among the first to explore UiPath innovative macOS automation capabilities. This is a must-attend session for developers eager to unlock the full potential of automation. 📕 This webinar will offer insights on: How to design, debug, and run automations directly on your Mac using UiPath Studio Web and UiPath Assistant for Mac. We’ll walk you through local debugging on macOS, working with native UI elements, and integrating with key tools like Excel on Mac. This is a must-attend session for developers eager to unlock the full potential of automation. 👨‍🏫 Speakers: Andrei Oros, Product Management Director @UiPath SIlviu Tanasie, Senior Product Manager @UiPath
Dev Dives: Unleash the power of macOS Automation with UiPathDev Dives: Unleash the power of macOS Automation with UiPath
Dev Dives: Unleash the power of macOS Automation with UiPath
UiPathCommunity
16 slides110 views
Designing for Multiple Blockchains in Industry Ecosystems by Dilum Bandara, has 22 slides with 51 views.Our proposed method employs a Design Structure Matrix (DSM) and Domain Mapping Matrix (DMM) to derive candidate shared ledger combinations, offering insights into when centralized web services or point-to-point messages may be more suitable than shared ledgers. We also share our experiences developing a prototype for an agricultural traceability platform and present a genetic-algorithm-based DSM and DMM clustering technique.
Designing for Multiple Blockchains in Industry EcosystemsDesigning for Multiple Blockchains in Industry Ecosystems
Designing for Multiple Blockchains in Industry Ecosystems
Dilum Bandara
22 slides51 views
Build with AI on Google Cloud Session #5 by Margaret Maynard-Reid, has 43 slides with 28 views.This is session #5 of the 5-session online study series with Google Cloud, where we take you onto the journey learning generative AI. You’ll explore the dynamic landscape of Generative AI, gaining both theoretical insights and practical know-how of Google Cloud GenAI tools such as Gemini, Vertex AI, AI agents and Imagen 3.
Build with AI on Google Cloud Session #5Build with AI on Google Cloud Session #5
Build with AI on Google Cloud Session #5
Margaret Maynard-Reid
43 slides28 views
How to manage technology risk and corporate growth by Arlen Meyers, MD, MBA, has 6 slides with 36 views.Board v management roles, holes, and goals. How to manage technology risk?
How to manage technology risk and corporate growthHow to manage technology risk and corporate growth
How to manage technology risk and corporate growth
Arlen Meyers, MD, MBA
6 slides36 views
The Rise of AI Agents-From Automation to Autonomous Technology by Impelsys Inc., has 11 slides with 22 views.AI agents are more than just a buzzword—they are transforming industries with real autonomy. Unlike traditional AI, they don’t just follow commands; they think, adapt, and act independently. The future isn’t just AI-enabled—it’s AI-powered.
The Rise of AI Agents-From Automation to Autonomous TechnologyThe Rise of AI Agents-From Automation to Autonomous Technology
The Rise of AI Agents-From Automation to Autonomous Technology
Impelsys Inc.
11 slides22 views
Don't just talk to AI, do more with AI: how to improve productivity with AI a... by All Things Open, has 19 slides with 95 views.Presented at All Things Open AI 2025 Presented by Sheng Liang - Acorn Labs Title: Don't just talk to AI, do more with AI: how to improve productivity with AI agents Find more info about All Things Open: On the web: https://www.allthingsopen.org/ Twitter: https://twitter.com/AllThingsOpen LinkedIn: https://www.linkedin.com/company/all-things-open/ Instagram: https://www.instagram.com/allthingsopen/ Facebook: https://www.facebook.com/AllThingsOpen Mastodon: https://mastodon.social/@allthingsopen Threads: https://www.threads.net/@allthingsopen Bluesky: https://bsky.app/profile/allthingsopen.bsky.social 2025 conference: https://2025.allthingsopen.org/
Don't just talk to AI, do more with AI: how to improve productivity with AI a...Don't just talk to AI, do more with AI: how to improve productivity with AI a...
Don't just talk to AI, do more with AI: how to improve productivity with AI a...
All Things Open
19 slides95 views
Ansible Variables in Playbook - RHCE.pdf by RHCSA Guru, has 11 slides with 34 views. Ansible variables is a key component in automation and configuration management - part of RHCE syllabus
Ansible Variables in Playbook - RHCE.pdfAnsible Variables in Playbook - RHCE.pdf
Ansible Variables in Playbook - RHCE.pdf
RHCSA Guru
11 slides34 views
Mastering NIST CSF 2.0 - The New Govern Function.pdf by Bachir Benyammi, has 42 slides with 78 views.Mastering NIST CSF 2.0 - The New Govern Function Join us for an insightful webinar on mastering the latest updates to the NIST Cybersecurity Framework (CSF) 2.0, with a special focus on the newly introduced "Govern" function delivered by one of our founding members, Bachir Benyammi, Managing Director at Cyber Practice. This session will cover key components such as leadership and accountability, policy development, strategic alignment, and continuous monitoring and improvement. Don't miss this opportunity to enhance your organization's cybersecurity posture and stay ahead of emerging threats. Secure your spot today and take the first step towards a more resilient cybersecurity strategy! Event hosted by Sofiane Chafai, ISC2 El Djazair Chapter President Watch the webinar on our YouTube channel: https://youtu.be/ty0giFH6Qp0
Mastering NIST CSF 2.0 - The New Govern Function.pdfMastering NIST CSF 2.0 - The New Govern Function.pdf
Mastering NIST CSF 2.0 - The New Govern Function.pdf
Bachir Benyammi
42 slides78 views
Revolutionizing GPU-as-a-Service for Maximum Efficiency by AI Infra Forum, has 30 slides with 17 views.In this session, we'll explore our cutting-edge GPU-as-a-Service solution designed to transform enterprise AI operations. Learn how our MemVerge.ai platform maximizes GPU utilization, streamlines workload management, and ensures uninterrupted operations through innovative features like Dynamic GPU Surfing. We'll dive into key use cases, from training large language models to enterprise-scale AI deployment. We'll demonstrate how our solution benefits various stakeholders – from platform engineers to data scientists and decision-makers. Discover how our platform optimizes costs while maintaining data security and sovereignty.
Revolutionizing GPU-as-a-Service for Maximum EfficiencyRevolutionizing GPU-as-a-Service for Maximum Efficiency
Revolutionizing GPU-as-a-Service for Maximum Efficiency
AI Infra Forum
30 slides17 views
Ansible Vault Encrypting and Protecting Secrets - RHCE.pdf by RHCSA Guru, has 17 slides with 37 views.Ansible Vault : Guide to encrypting, decrypting, and managing sensitive data securely in Ansible playbooks - part of RHCE syllabus
Ansible Vault Encrypting and Protecting Secrets - RHCE.pdfAnsible Vault Encrypting and Protecting Secrets - RHCE.pdf
Ansible Vault Encrypting and Protecting Secrets - RHCE.pdf
RHCSA Guru
17 slides37 views
Event-driven and serverless in the world of IoT by Jimmy Dahlqvist, has 54 slides with 35 views.Presentation for AWS Community Day Slovakia around Event-driven and serverless in the world of IoT
Event-driven and serverless in the world of IoTEvent-driven and serverless in the world of IoT
Event-driven and serverless in the world of IoT
Jimmy Dahlqvist
54 slides35 views
Rens van de Schoot - Mensen, machines en de zoektocht naar het laatste releva... by voginip, has 75 slides with 26 views.Keynote bij de VOGIN-IP-lezing, 27 maart 2025, OBA Amsterdam
Rens van de Schoot - Mensen, machines en de zoektocht naar het laatste releva...Rens van de Schoot - Mensen, machines en de zoektocht naar het laatste releva...
Rens van de Schoot - Mensen, machines en de zoektocht naar het laatste releva...
voginip
75 slides26 views
TrustArc Webinar: Strategies for Future-Proofing Privacy for Healthcare by TrustArc, has 16 slides with 199 views.With increasing attention to healthcare privacy and enforcement actions proposed with the HIPPA Privacy Rules Changes planned for 2025, healthcare leaders must understand how to grow and maintain privacy programs effectively and have insights into their privacy methods. Indeed, the healthcare industry faces numerous new challenges, including the rapid adoption of virtual health and other digital innovations, consumers’ increasing involvement in care decision-making, and the push for interoperable data and data analytics. How can the industry adapt? Join our panel on this webinar as we explore the privacy risks and challenges the healthcare industry will likely encounter in 2025 and how healthcare organizations can use privacy as a differentiating factor. This webinar will review: - Current benchmarks of privacy management maturity in healthcare organizations - Upcoming data privacy vulnerabilities and opportunities resulting from healthcare’s digital transformation efforts - How healthcare companies can differentiate themselves with their privacy program
TrustArc Webinar: Strategies for Future-Proofing Privacy for HealthcareTrustArc Webinar: Strategies for Future-Proofing Privacy for Healthcare
TrustArc Webinar: Strategies for Future-Proofing Privacy for Healthcare
TrustArc
16 slides199 views
IObit Driver Booster Pro Crack 12.2.0 with License Key [2025] by jamesfolkner123, has 1 slides with 61 views.COPY & PASTE LINK👉👉👉https://serialsofts.com/dl/ IOBIT Driver Booster Pro is an application that can update all the drivers and game components present on the computer.
IObit Driver Booster Pro Crack 12.2.0 with License Key [2025]IObit Driver Booster Pro Crack 12.2.0 with License Key [2025]
IObit Driver Booster Pro Crack 12.2.0 with License Key [2025]
jamesfolkner123
1 slide61 views
Achieving Extreme Scale with ScyllaDB: Tips & Tradeoffs by ScyllaDB, has 65 slides with 40 views.Explore critical strategies – and antipatterns – for achieving low latency at extreme scale If you’re getting started with ScyllaDB, you’re probably intrigued by its potential to achieve predictable low latency at extreme scale. But how do you ensure that you’re maximizing that potential for your team’s specific workloads and technical requirements? This webinar offers practical advice for navigating the various decision points you’ll face as you evaluate ScyllaDB for your project and move into production. We’ll cover the most critical considerations, tradeoffs, and recommendations related to: - Infrastructure selection - ScyllaDB configuration - Client-side setup - Data modeling Join us for an inside look at the lessons learned across thousands of real-world distributed database projects.
Achieving Extreme Scale with ScyllaDB: Tips & TradeoffsAchieving Extreme Scale with ScyllaDB: Tips & Tradeoffs
Achieving Extreme Scale with ScyllaDB: Tips & Tradeoffs
ScyllaDB
65 slides40 views
Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ... by All Things Open, has 32 slides with 22 views.Presented at All Things Open AI 2025 Presented by Shivay Lamba - Couchbase Title: ​​Fine-Tuning Large Language Models with Declarative ML Orchestration Abstract: Large Language Models used in tools like ChatGPT are everywhere; however, only a few organisations with massive computing resources are capable of training such large models. While eager to fine-tune these models for specific applications, the broader ML community often grapples with significant infrastructure challenges. In the session, the audience will understand how open-source ML tooling like Flyte (a Linux Foundation open-source orchestration platform) can be used to provide a declarative specification for the infrastructure required for a wide array of ML workloads, including the fine-tuning of LLMs, even with limited resources. Thus the attendee will learn how to leverage open-source ML toolings like Flyte's capabilities to streamline their ML workflows, overcome infrastructure constraints, reduce cost and unlock the full potential of LLMs in their specific use case. Thus making it easier for a larger audience to leverage and train LLMs. Find more info about All Things Open: On the web: https://www.allthingsopen.org/ Twitter: https://twitter.com/AllThingsOpen LinkedIn: https://www.linkedin.com/company/all-things-open/ Instagram: https://www.instagram.com/allthingsopen/ Facebook: https://www.facebook.com/AllThingsOpen Mastodon: https://mastodon.social/@allthingsopen Threads: https://www.threads.net/@allthingsopen Bluesky: https://bsky.app/profile/allthingsopen.bsky.social 2025 conference: https://2025.allthingsopen.org/
Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ...Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ...
Fine-Tuning Large Language Models with Declarative ML Orchestration - Shivay ...
All Things Open
32 slides22 views
SAP Business Data Cloud: Was die neue SAP-Lösung für Unternehmen und ihre Dat... by IBsolution GmbH, has 24 slides with 20 views.Inhalt: Daten spielen für jede Business-Transformation eine entscheidende Rolle. Mithilfe der SAP Business Data Cloud (BDC) sind Unternehmen in der Lage, sämtliche Daten miteinander zu verbinden und zu harmonisieren. Die SAP BDC stellt eine Weiterentwicklung der bisherigen SAP-Datenstrategie dar - mit SAP Datasphere und der SAP Analytics Cloud (SAC) als elementaren Säulen. Besonders hervorzuheben: Databricks ist als OEM-Produkt in die Architektur integriert. Die SAP BDC kombiniert neue und bestehende Technologien, um Anwendern angereicherte Datenprodukte, fortschrittliche Analyse-Funktionalitäten und KI-gestützte Insights-Anwendungen bereitzustellen. Kurz gesagt: Mit SAP BDC schaffen Unternehmen eine zentrale Drehscheibe für ihre geschäftskritischen Daten und legen die Basis für SAP Business AI. In unserem Expertengespräch erläutern Stefan Hoffmann (Head of Cross Solution Management SAP HANA & Analytics bei SAP) und Martin Eissing (Projektmanager bei IBsolution), was es mit der SAP Business Data Cloud genau auf sich hat und welche konkreten Vorteile mit dem neuen Angebot einhergehen. Außerdem zeigen sie auf, wie das erste Feedback der Kunden zur SAP BDC ausfällt und welche Wege Unternehmen zur SAP BDC führen. Zielgruppe: - IT-Leiter/IT-Entscheider - Data Analysts - Datenarchitekten - BI-Spezialisten - Anwender in den Fachbereichen Agenda: 1. Was ist die SAP Business Data Cloud (BDC)? 2. Einordnung in die SAP-Datenstrategie 3. Voraussetzungen und Mehrwerte der SAP BDC 4. Architektur der SAP BDC 5. Handlungsempfehlungen für SAP BW-Kunden und SAP Datasphere-Kunden 6. Q&A
SAP Business Data Cloud: Was die neue SAP-Lösung für Unternehmen und ihre Dat...SAP Business Data Cloud: Was die neue SAP-Lösung für Unternehmen und ihre Dat...
SAP Business Data Cloud: Was die neue SAP-Lösung für Unternehmen und ihre Dat...
IBsolution GmbH
24 slides20 views
Safer’s Picks: The 6 FME Transformers You Didn’t Know You Needed by Safe Software, has 56 slides with 226 views.With over 500 transformers in FME, it’s easy to stick to your favourites – but what about the hidden gems that could help you achieve more than you thought possible in your workspaces? In this lightning talk-style webinar, our Safe team panel of FME Experts will highlight underutilized transformers and clever techniques that can make your workflows more powerful, efficient, and dynamic. Whether it’s a transformer you’ve never explored before or an unexpected way to use an old favourite, you’re sure to walk away with new ideas to enhance your FME skills. Transformers they’ll cover include: Donal, the MapnikRasterizer: Learn how to generate high-quality raster outputs from vector data with precise control over symbolization and labelling Crystal, the SchemaScanner: Detect schema drift on the fly and dynamically set your output schema based on incoming data. Mark, the ModuloCounter: Discover how to group features efficiently using the number of groups, rather than group size. Evie, the Aggregator: See how versatile it can be for concatenating, listing, and joining data as an alternative to other transformers. Natalie, the RasterExpressionEvaluator: Simplify raster expressions using presets to make them repeatable and easy to manage. Dave, the ChangeDetector: Fine-tune output configurations to pinpoint exactly what’s changed in your data. Join us for this fast-paced, insight-packed session and uncover the FME transformers you didn’t know you needed!
Safer’s Picks: The 6 FME Transformers You Didn’t Know You NeededSafer’s Picks: The 6 FME Transformers You Didn’t Know You Needed
Safer’s Picks: The 6 FME Transformers You Didn’t Know You Needed
Safe Software
56 slides226 views

jQuery Proven Performance Tips & Tricks

  • 1. jQuery Proven PERFORMANCE TIPS & TRICKS WITH ADDY OSMANI IMAGES COPYRIGHT HASBRO AND TONKA, 1935-2011. and Mr. Monopoly
  • 2. ABOUT ME • JavaScript & UI Developer at Aol • jQuery Core [Bugs/Docs/Learning] teams • SocketStream Core Team Member • Writer [Script Junkie / AddyOsmani.com/.net etc]
  • 3. We used to give out these awesome free coasters back in the 90s.
  • 4. We now create real-time web frameworks and next-gen platforms.
  • 5. Enough of that.. LET’S START!
  • 6. WHY DOES PERFORMANCE MATTER? • Apps should be snappy, not sloppy. • Best practices offer optimal approaches to solving problems. • If we don’t follow them, browsers can end up having to do more work.
  • 7. MORE WORK = MORE MEMORY USE = SLOWER APPS.
  • 8. TODAY, ALL OF THESE SLIDES COME WITH PERFORMANCE TESTS. Not just saying X is faster...we’re proving it too.
  • 9. PERFORMANCE TESTING • jsPerf.com - a great way to easily create tests comparing the performance of code snippets across different browsers • Makes it simple for anyone to share or modify tests • Used by the jQuery project, Yahoo and many other dev. teams Thanks to Mathias Bynens for creating it!
  • 10. Example of test output Anyone can tell what the fastest and slowest snippets are. http://jsperf.com/jquery-tree-traversing
  • 11. Quick jsPerf tips for beginners • ops/sec is the number of times a test is projected to execute in a second • Tests get repeatedly executed until they reach the minimum time required to get a percentage uncertainly • Results based on ops/sec accounting for margin of error. The higher ops/sec the better.
  • 12. 1 PERFORMANCE TIP
  • 13. STAY UP TO DATE! • Always use the latest version of jQuery core where possible. • Remember to regression test your scripts and plugins before upgrading. • Current version is 1.6.2 and 1.7 will probably get released this fall.
  • 14. MOST POPULAR SITES USING JQUERY ON THE GOOGLE CDN Old Stats from Scott Mitchell
  • 15. INTERESTING FACTS • Performance improvements and new features usually land in major releases (eg. 1.6/1.x) • Bug patches and regression fixes land in 1.x.y releases (eg. 1.6.2) • Plenty of reasons to upgrade!
  • 16. WHY? • Older versions won’t offer these instant performance benefits • As 47% of the popular sites on the web use jQuery, changes are heavily tested. • Upgrading usually a pain-free process.
  • 17. Selector comparisons1.4.2 vs. 1.4.4 vs. 1.6.2 1.4.2 1.4.4 1.6.2 $(’.elem’) $(’.elem’, context); context.find(’.elem’); 0 27500 55000 82500 110000 http://jsperf.com/jquery-1-4-2-vs-1-6-2-comparisons
  • 18. 1.6.x improvements .attr() performance improved .val() faster in 1.6.x http://jsperf.com/attr-vs-attrhooks http://jsperf.com/valhooks-vs-val/2
  • 19. Note • There are certain selectors that are slower in 1.6.x than they are in 1.4.x • Be aware of the performance of selectors you’re using and you’ll be fine
  • 20. 2 PERFORMANCE TIP
  • 21. KNOW YOUR SELECTORS • All selectors are not created equally • Just because a selection can be made in many ways, doesn’t mean each selector is just as performant • Do you know what the fastest to slowest selectors are?
  • 22. Fast: ID & Element Selectors $(‘#Element,  form,  input’) • ID and element selectors are the fastest • This is because they’re backed by native DOM operations (eg. getElementById()).
  • 23. Slower: Class Selectors $(‘.element’) • getElementsByClassName() not supported in IE5-8 • Supported in FF3+, Safari 4+, Chrome 4+, Opera 10.10+ so faster in these. http://www.quirksmode.org/dom/w3c_core.html
  • 24. Slowest: Pseudo & Attribute Selectors $(‘:visible,  :hidden’);   $(‘[attribute=value]’); • This is due to no native calls available that we can take advantage of. • querySelector() and querySelectorAll() help with this in modern browsers. http://www.quirksmode.org/dom/w3c_core.html
  • 25. querySelectorAll() • Allows searching the DOM for elems based on a CSS selector in modern browsers. • jQuery attempts to use qSA without hitting Sizzle for queries including $(‘#parent .child’) or $(‘.parent a[href!=”hello”]’) • Optimise for selectors that use qSA vs. those that don’t such as :first, :last, :eq etc. • Valid selectors have a better chance of using it.
  • 26. jsPerf selector comparison 1.4.2 1.6.2 ID Class Descendent tag Attributes Input/form select :nth-child 0 75000 150000 225000 300000 http://jsperf.com/dh-jquery-1-4-vs-1-6/6
  • 27. BUT I’M TOO PRETTY TO GO TO JAIL! Pseudo-selectors are powerful..but slow, so be careful when using them.
  • 28. The :hidden pseudo-selector if ( jQuery.expr && jQuery.expr.filters ) {     jQuery.expr.filters.hidden = function( elem ) {         var width = elem.offsetWidth,             height = elem.offsetHeight;         return (width === 0 && height === 0) ||(!jQuery.support.reliableHiddenOffsets && (elem.style.display ||jQuery.css( elem, "display" )) === "none");     };     jQuery.expr.filters.visible = function( elem ) {         return !jQuery.expr.filters.hidden( elem );     }; } • Looking at the code, why is this bad?
  • 29. Be careful because.. • If you use this with 100 elements, jQuery calls it 100 times. • :hidden is powerful but like all pseudos must be run against all the elements in your search space. • If possible, avoid them!.
  • 30. jsPerf performance tests • jQuery1.4.2 vs 1.6 selector comparison tests http://jsperf.com/dh-jquery-1-4-vs-1-6/6 • jQuery 1.2.x vs 1.4.x vs. 1.6.x vs. qSA vs. qS vs. other frameworks http://jsperf.com/jquery-vs- sizzle-vs-midori-vs-mootools-selectors-test/26
  • 31. 3 PERFORMANCE TIP
  • 32. UNDERSTAND PARENTS AND CHILDREN 1) $(‘.child", $parent).show(); //context 2) $parent.find(‘.child’).show(); //find() 3) $parent.children(".child’).show(); //immediate children 4) $(‘#parent > .child’).show(); //child combinator selector 5) $(‘#parent .child’).show(); //class selector 6) $('.child', $('#parent')).show(); //created context
  • 33. Context 1)  $(‘.child’,  $parent).show();   • Here the scope must be parsed and translated to $.parent.find(‘child’).show(); causing it to be slower. • ~5-10% slower than the fastest option
  • 34. .find() 2)  $parent.find(‘.child’).show();   • This is the fastest of the entire set. I’ll explain why shortly.
  • 35. Immediate children 3)  $parent.children(‘.child’).show();   • Internally uses $.sibling and JavaScript’s nextSibling() to find nodes following other nodes in the same tree. • ~50% slower than the fastest option
  • 36. CSS child combinator selector 4)  $(‘#parent  >  .child’).show(); • Uses a child combinator selector, however Sizzle works from right to left. • Bad as it will match .child before checking it’s a direct child of the parent. • ~70% slower than the fastest option
  • 37. CSS class selector 5)  $(‘#parent  .child’).show();   • Uses a class selector and is constrained by the same rules as 4). • Internally also has to translate to using .find() • ~77% slower than the fastest option
  • 38. Created context 6)  $(‘.child’,  $(‘#parent’)).show();   • Equivalent internally to $(‘#parent’).find(‘.child’), however note that parent is a jQuery object. • ~23% slower than the fastest option
  • 39. The fastest option is.. 2)  $parent.find(‘.child’).show();   • The parent selector is already cached here, so it doesn’t need to be refetched from the DOM. • Without caching this is ~ 16% slower. • Directly uses native getElementById, getElementsByName, getElementsByTagName to search inside the passed context under the hood.
  • 40. It’s worth noting.. • .find() performs a recursive top-down search of all child and sub-elements • Other options presented may be more suitable/performant depending on what you’re trying to achieve.
  • 41. jsPerf performance tests • context vs. selector vs. selector and .find() vs. parent/child selector vs. immediate children: http://jsperf.com/jquery- selectors-context/2
  • 42. 4 PERFORMANCE TIP
  • 43. Don’t use jQuery unless it’s absolutely necessary • Remember it’s sometimes more performant to use regular ol’ JavaScript • jQuery is JavaScript so there’s no harm. • How many times have you done this..
  • 44. Eg. jQuery over-use of attr() $('a').bind(‘click’, function(){   console.log('You clicked: ' + $(this).attr('id')); }); • jQuery’s ID selector only gets to document.getElementById after parsing the selector and creating a jQuery object
  • 45. Why not use the DOM element itself? This is faster: $('a').bind(‘click’, function(){   console.log('You clicked: ' + this.id); }); • Avoid the overhead by remembering the jQuery-way isn’t always the best way.
  • 46. Quick note: • this.id and $(this).attr(‘id’) both return the same value but remember.. • At a lower-level, this.getAttribute(‘id’) is equivalent to $(this).attr(‘id’); • However, as the attribute stays up to date, this.id is still better to use.
  • 47. jsPerf Performance tests • $(this).attr(‘id’) vs. this.id http://jsperf.com/ el-attr-id-vs-el-id/2 • Using the former is actually 80-95% slower than directly accessing the attribute through the DOM element.
  • 48. 5 PERFORMANCE TIP
  • 49. CACHING IS YOUR FRIEND. var parents =  $(‘.parents’), //caching children = $(‘.parents’).find(‘.child’), //bad kids = parents.find(‘.child’); //good • Caching just means we’re storing the result of a selection for later re-use.
  • 50. So remember.. • Each $(‘.elem’) will re-run your search of the DOM and return a new collection • You can then do anything with the cached collection. • Caching will decrease repeat selections.
  • 51. Doing just about anything with the cached collection. var foo = $(‘.item’).bind('click', function({         foo.not(this).addClass(‘bar’)                   .removeClass(‘foobar’)                   .fadeOut(500); });
  • 52. jsPerf performance tests • Comparing the performance of cached selectors vs. repeated element selections http://jsperf.com/ns-jq-cached • Uncached selectors in these tests are anywhere up to 62% slower than their cached equivalents.
  • 53. 6 PERFORMANCE TIP
  • 54. CHAINING var parents =  $(‘.parents’).doSomething().doSomethingElse(); • Almost all jQuery methods return a jQuery object and support chaining. • This means after executing a method on a selection, you can continue executing more. • Less code and it’s easier to write!
  • 55. No-chaining vs. chaining //Without  chaining $(‘#notification’).fadeIn(‘slow’); $(‘#notification’).addClass(‘.activeNotification’); $(‘#notification’).css(‘marginLeft’,  ‘50px’); //With  chaining $(‘#notification’).fadeIn(‘slow’)                                    .addClass(‘.activeNotification’)                                          .css(‘marginLeft’,  ‘50px’);
  • 56. jsPerf performance tests • Chained calls vs. separate calls vs. cached separate calls http://jsperf.com/jquery-chaining • Chaining is the fastest followed by cached separate calls.
  • 57. 7 PERFORMANCE TIP
  • 58. EVENT DELEGATION • The idea that you allow events to bubble up the DOM tree to a parent element. • Important as it allows you to only bind a single event handler rather than 100s. • Works with elements in the DOM at runtime (and those injected later)
  • 59. .bind() • Allows you to attach a handler to an event such as ‘click’, ‘mouseenter’ etc for elements • With larger sets, the browser has to keep track of all event handlers and this can take time to bind. • Doesn’t work with dynamically inserted elements.
  • 60. .live() • Simplest form of supported event delegation • Allows you to attach a handler to an event for current and future matches of a selector • Works best for simple scenarios but has flaws (has to be at the top of the chain, fails alongside traversals) • Can’t chain to it, unlike other jQuery methods.
  • 61. .delegate() • Allows you to specify the particular DOM element would like to bind to when attaching handlers to selections that match current/future elems. • Ensures we don’t bubble all the way up the DOM to capture an element’s target (unlike .live()) • Use when binding the same event handler to multiple elements
  • 62. jsPerf performance tests • .live() vs .delegate() vs. delegate from body variations http://jsperf.com/jquery-delegate-vs-live-table-test/2 • .bind() vs .click() vs. live() vs. delegate() http:// jsperf.com/bind-vs-click/12 • .live() vs .live() context vs .delegate() vs. delegating to document.body http://jsperf.com/jquery-live-vs- jquery-delegate/15
  • 63. 8 PERFORMANCE TIP
  • 64. THE DOM ISN’T A DATABASE • jQuery allows you to treat it like one but it isn’t. • Remember each DOM insertion is costly. • This means keep the use of .append (), .insertBefore(), .insertAfter() etc. to a minimum.
  • 65. It’s also important to remember • Traversing the DOM to retrieve content or information stored in .text(), .html() etc is not the most optimal approach. • This could be in .data() instead, which allows us to attach any type of data to DOM elements safely.
  • 66. Tip 1: Better .append() usage • Minimise use by building HTML strings in- memory and using a single .append() instead. • Multiple appends can be up to 90% slower when not appending to cached selectors and up to 20% slower with them.
  • 67. Tip 2: Use .detach() • Works great when you’re doing heavy interaction with a node • Allows you to re-insert the node to the DOM once you’re ready • Up to 60% faster than working with undetached nodes.
  • 68. .detach() example $(‘p’).click(function(){       $(this).toggleClass(‘off’); }); var p; $(‘button’).click(function(){       if ( p ) { /*..additional modification*/         p.appendTo(‘body’);         p = null;       } else {         p = $(‘p’).detach();       } });
  • 69. Tip 3: Better .data() usage • We usually attach data like this.. $(‘#elem’).data(  key  ,  value  ); • But this is actually much faster.. $.data(‘#elem’,  key  ,  value); • as there’s overhead creating a jQuery object and doing data-parsing in the first.
  • 70. Notes • Although $.data is faster, it cannot be passed a selector, only a node. • This means $.data(elem, key, value) works where elem is already defined as an element.
  • 71. jsPerf performance tests • .detach() vs not detaching http:// jsperf.com/to-detach-or-not-to-detach • jQuery.data vs jQuery.fn.data: http:// jsperf.com/jquery-data-vs-jqueryselection- data/11 • Multiple appends vs a single append http:// jsperf.com/string-concat-single-append-vs- multiple-append
  • 72. 9 PERFORMANCE TIP
  • 73. UNDERSTAND LOOPS • Did you know that native for and while loops are faster than using $.each() and $.fn.each()? • jQuery makes it easy to iterate over collections, but remember it’s not always the most performant option. • Plugins like Ben Alman’s $.each2() sometimes perform better than $.fn.each
  • 74. AVOID LOOPS IF YOU CAN. HARD, BUT NESTED DOM SELECTORS MAY PERFORM BETTER. • Unless absolutely necessary, avoid loops. They’re slow in every programming language. • If possible, use the selector engine instead to access the elements needed. • There are of course places loops cannot be substituted but try your best to optimise.
  • 75. That said.. • Developers often need to iterate • The closure-scope provided by $.each is usually required for other reasons. • Should loops be such a pain-point you need to unroll them you’re lucky, but remember there are alternatives possible.
  • 76. jsPerf performance tests • jQuery.each vs. for, while, reverse for, jQuery.fn.each and other loop approaches: http:// jsperf.com/jquery-each-vs-for-loop/24 • jQuery.fn.each vs Ben Alman’s .each2() http:// jsperf.com/jquery-each-vs-quickeach/3
  • 77. PERFORMANCE TIP 10
  • 78. Avoid constructing new jQuery objects unless necessary $(‘a’).map(function(){ return $(this).text();}); • Developers commonly create new jQuery objects on iterations such as the above just to access some text • Using a lower-level method like $.method() rather than $.fn.method() can help improve performance with this. Thanks to James Padolsey for this tip
  • 79. $.text vs $.fn.text http://jsperf.com/jquery-text-vs-html/5
  • 80. Notes: • Not all jQuery methods have their own single- node functions • James proposed jQuery.single() as a solution to this problem • It uses a single jQuery object for all calls to jQuery.single() and only works for single DOM elements. http://james.padolsey.com/javascript/76-bytes-for-faster-jquery/
  • 81. Bonus Tip
  • 82. KEEP YOUR CODE DRY • Repeating the same code increases the size of your code-base and reduces productivity • DRY (don’t repeat yourself) encourages one representation of each piece of knowledge • Keeping code minimal can also remind you that chaining, caching etc can assist with this.
  • 83. Let’s go through a quick example.. /*Let's store some default values to be read later*/ var defaultSettings = {}; defaultSettings['carModel']   = 'Mercedes'; defaultSettings['carYear’]    = 2012; defaultSettings['carMiles']   = 5000; defaultSettings['carTint']    = 'Metallic Blue';  
  • 84. Non-DRY code $('.someCheckbox').click(function(){    if ( this.checked ){                         $('#input_carModel').val(defaultSettings.carModel);         $('#input_carYear').val(defaultSettings.carYear);         $('#input_carMiles').val(defaultSettings.carMiles);         $('#input_carTint').val(defaultSettings.carTint);    } else {                  $('#input_carModel').val('');              $('#input_carYear').val('');         $('#input_carMiles').val('');         $('#input_carTint').val('');  } });
  • 85. DRY code var props = ['carModel', 'carYear', 'carMiles', 'carTint']; $('.someCheckbox').click(function(){             var checked = this.checked;     /*         What are we repeating?         1. input_ precedes each field name         2. accessing the same array for settings         3. repeating value resets            What can we do?         1. programmatically generate the field names         2. access array by key         3. merge this call using terse coding (ie. if checked,             set a value, otherwise don't)     */          $.each(props,function(i,key){                $('#input_' + key).val(checked ? defaultSettings[key] : '');        }); });
  • 86. THANKS. • Props to Adam Sontag, JD Dalton, Paul Irish, Timmy Willison, James Padolsey, Mathias Bynens, Matt Baker and the team @jquery • For more on me: • http://addyosmani.com • @addyosmani
  • 87. THAT’S IT! GO BUILD AWESOME THINGS.