SlideShare a Scribd company logo
jQueryTips, tricks and hints
   for better development and performance




Jonas De Smet - @glamorous_be - BarcampGhent 2009
Who am I ?!
Jonas De Smet
- 23 years “old” developer
- Fan of PHP, jQuery and JSON
- Barcamp virgin

- Lives in Waregem
- Plays rugby with RC Curtrycke
- In love with Eline, the girl of
  his life
Why are you
 here ?!
jQuery: Tips, tricks and hints for better development and Performance
Todays Schedule
✓ What is jQuery?
✓ 10 Usefull tips for better development
✓ 10 Performance tips
✓ Some Q’s & hopefully some A’s
What is jQuery?
-   JavaScript Library
-   Easy document traversing
-   Easy event handling
-   Rapid web development
-   ...

“jQuery is designed to change the way that you write JavaScript”
                       (from jQuery.com)
What is jQuery?
var elems = document.getElementsByTagName(“p”);
for(var i=0;i<elems.length;i++){
    if(elems[i].className == “example”){
     elems[i].onclick = function(){
         alert(“this example doesn’t rocks!”);
         this.className += “ clicked”;
         return false;
     }
}
What is jQuery?
$(“p.example”).click(function(){
      $(this).addClass(“clicked”);
      alert(“this example rocks!”);
      return false;
});
Usefull tips
 for better development
Usefull tips - #1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

 <title>Title of the page</title>

 <meta http-equiv="content-type" content="text/html;charset=utf-8" />


 <script type="text/javascript">document.documentElement.className = 'js';</script>

 <link rel="stylesheet" href="/style.css" type="text/css" media="screen" />
</head>




                        Avoid flashing content
Usefull tips - #2
function testFunction()
{
   console.time(‘test this cool function’);
   var testString = “”;
   for(i=0; i<1000; i++)
   {
      testString += “item ” + i;
   }
   console.timeEnd(‘test this cool function’);
}

//time will be logged in milliseconds



          Use Firebug’s console loggings facilities
Usefull tips - #3
<script type=”text/javascript” src=”http://www.google.com/jsapi”></script>
<script type=”text/javascript”>
  google.load(“jquery”, “1.3.2”);
  google.setOnLoadCallback(function() {
      //init your javascript code
  });
</script>


<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/
jquery.min.js”></script>




                  Load jQuery from Google Code
Usefull tips - #4
<div class=”expanded”>                     <div>
  <p>Some lorem ipsum</p>                    <p>Some lorem ipsum</p>
  <span class=”btn”>Close</span>             <span class=”btn”>Close</span>
</div>                                     </div>

  $(“.btn”).click(function() {               $(“.btn”).click(function() {
    var parent = $(this).parent();             var parent = $(this).parent();
    if ( parent.hasClass(“expanded”) ) {       if ( parent.data(“expanded”) ) {
        parent.removeClass(“expanded”);            parent.data(“expanded”, false);
    }                                          }
    else {                                     else {
        parent.addClass(“expanded”);               parent.data(“expanded”, true);
    }                                          }
  }                                          }


   Storing states in classes or even better in .data()
Usefull tips - #5
$.expr[“:”]:extlinks = function(element){
   var link = $(element).attr(“href ”);
   var reg = new RegExp('^(?:f|ht)tp(?:s)?://([^/]+)', 'im');
   var link_host = (link.match(re) != null) ? link.match(re)[1].toString() : “”;
   var host = window.location.host;
   return (link_host != host);
}


$(“a:extlinks”).attr(“target”,”_blank”);

<h3>Some links</h3>
<a href=”http://example.com”>Example</a>
<a href=”/intern/folder/”>Example</a>

                      Write custom filter selectors
Usefull tips - #6
function uglyObject()
{
   //some object stuff
}

var example = new uglyObject();

$(example).bind(‘addFancy’, function() {
    // Custom event handling for when the event ‘addFrancy’ is triggered
});

$(example).trigger(‘addFancy’);




             Bind custom events to custom objects
Usefull tips - #7
if ($(“div”).length){
    //code here
}

if ($(“div”)[0]){
    // code here
}

// Alternatively
$(“div”).get();

$(“div”).get(0);
$(“div”).get()[0];



                        Check if an element exists
Usefull tips - #8
// List bound events:
console.dir( $(“#elem”).data(“events”) );


// Log ALL handlers for ALL events:
$.each($(“#elem”).data(“events”), function(i, event)
{
    jQuery.each(event, function(i, handler){
        console.log( handler.toString() );
    });
});

// source: http://james.padolsey.com



                      Use jQuery’s event storage
Usefull tips - #9
$(“a”).bind(“click.myNamespace”, function() {
    // Some code for the click event with namespace “myNamespace”
});

// Unbind all events with namespace “myNamespace”
$(“a”).bind(“click.my2ndNamespace”, function(){
    // Some code for the click event with namespace “my2ndNamespace”
});

// Unbind events with namespace “myNamespace”, not events with “my2ndNamespace”
$(“a”).unbind(“.myNamespace”);


$(“#example”).data(“nameValue.aNameSpace”, “teststring”);


       Namespace your events and stored data
Usefull tips - #10
$(“p”).click(somefunction);

$(“p span”).click(somefunction);

$(“p a”).click(somefunction);


// You can do the above easily in one line
$(“p, p a, p span”).click(somefunction);




                     Try to group your queries
Performance
    Tips
Performance tips - #1
var $specialdiv = $(“#specialdiv”);

$specialdiv.filter(function(){
    return $(this).hasClass(“clicked”); // Must return a Boolean
});
$specialdiv.filter(“.clicked”);


var $specialdiv = $(“#specialdiv”);

// before
var $specialspan = $(“#specialdiv span.on”);
// much better
var $specialspan = $specialdiv.find(“span.on”);


  Use .find() or .filter() instead of a new selector
Performance tips - #2
                           1. Use id’s before tags
$(“#mydiv”).addClass(“test”);


                      2. Use tags before classes
$(“p”).addClass(“test”);


                       3. Use classes with a tag
$(“p.example”).addClass(“test”);
Performance tips - #3
var items = $(“.coolDivs”, $(“#anotherDiv”) );

// or

var items = $(“#anotherDiv .coolDivs”);

// or even better

var items = $(“#anotherDiv div.coolDivs”);

//or

var items = $(“div.coolDivs”, $(“#anotherDiv”) );


                      Give selectors a context
Performance tips - #4
var $bigInputs = $(“#exampleForm input.big”);
$bigInputs.bind(“click”, clickfunction);
$bigInputs.addClass(“finished”);

// You can define an object in the global scope and access it later

window.$myobject = { test: $(“#divWithId”) };
$myobject.test.addClass(“yes”);

// Cache added elements to access them later instead of using .live()

var $newDiv = $(“<div />”).appendTo(“#anotherDiv”);
$newDiv.bind(“click”, clickfunction);



        Cache jQuery objects and use a $-prefix
Performance tips - #5
var $myElement = $(“#element”);

$myElement.css(“border”, “1px solid orange”).addClass(“bordered”).fadeIn(“fast”);

// another example
$myElement.find(“p”).addClass(“yellow”).end().find(“span”).css(“border”,”1px”);


// Make you plugins chainable!
$.fn.myPlugin = function()
{
   return $(this).addClass(“coolstuff ”);
};



 Chaining FTW, especially for plugin-development
Performance tips - #6
                                       //Wrap everything in one element

var $list = $(“#mylist”);              var $list = $(“#mylist”);
var str = “”;                          var wrapped = “<ul>”;

for (i=0; i < 100; i++)                for (i=0; i < 100; i++)
{                                      {
   str += “<li>item “ + i + ”</li>”;      wrapped += “<li>item “ + i + ”</li>”;
}                                      }

$list.html(str);                       wrapped += “</ul>”;

                                       $list.replaceWith(wrapped);



Avoid DOM manipulation & keep it to a minimum
Performance tips - #7
var $myList = $(“#navigation”);

$myList.click(function(evt){
    $target = $(evt.target);
    if($target.is(“li”) )
    {
           doSomethingWhenListItemIsClicked();
    }
    return false;
});

// more about jQuery events on http://docs.jquery.com/Events/jQuery.Event




                   Event delegation / bubbling
Performance tips - #8
var arr = [ "one", "two", "three", "four", "five" ];

$.each(arr, function() {
    $("#" + this).text("My id is " + this + ".");
});



var arr = [ "one", "two", "three", "four", "five" ];

for ( i=0; i < arr.length; i++ ) {
     $("#" + i).text("My id is " + i + ".");
});



                 Use a for-loop instead of .each()
Performance tips - #9
         Use shorthand for $(document).ready()
$(function () {
    // your code
});


            Use $(window).load() when possible
$(window).load( function () {
  // your code to be excuted when every HTML element is loaded
}

   $(document).ready occurs during page render while objects are downloading
      $(window).load() event occurs after all objects are called by the HTML
Performance tips - #10


Pack and minify your custom scripts (in one)

           http://javascriptcompressor.com
           http://dean.edwards.name/packer
Q &A
Thank you for listening!
Twitter @glamorous_be


Github http://github.com/glamorous
Slideshare http://www.slideshare.net/glamorous
LinkedIn http://be.linkedin.com/in/glamorous

More Related Content

What's hot (20)

Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Balázs Tatár
 
Let's write secure Drupal code!
Let's write secure Drupal code!Let's write secure Drupal code!
Let's write secure Drupal code!
Balázs Tatár
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Balázs Tatár
 
Intro to advanced caching in WordPress
Intro to advanced caching in WordPressIntro to advanced caching in WordPress
Intro to advanced caching in WordPress
Maor Chasen
 
Jquery introduction
Jquery introductionJquery introduction
Jquery introduction
musrath mohammad
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019
Balázs Tatár
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
NexThoughts Technologies
 
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Balázs Tatár
 
Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
Rafael Felix da Silva
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
Rebecca Murphey
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Balázs Tatár
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 
Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3
makoto tsuyuki
 
My shell
My shellMy shell
My shell
Ahmed Salah
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
Marco Vito Moscaritolo
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
Windows Azure Storage & Sql Azure
Windows Azure Storage & Sql AzureWindows Azure Storage & Sql Azure
Windows Azure Storage & Sql Azure
Maarten Balliauw
 
jQuery
jQueryjQuery
jQuery
Dileep Mishra
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
Remy Sharp
 
Assetic (Zendcon)
Assetic (Zendcon)Assetic (Zendcon)
Assetic (Zendcon)
Kris Wallsmith
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Balázs Tatár
 
Let's write secure Drupal code!
Let's write secure Drupal code!Let's write secure Drupal code!
Let's write secure Drupal code!
Balázs Tatár
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Balázs Tatár
 
Intro to advanced caching in WordPress
Intro to advanced caching in WordPressIntro to advanced caching in WordPress
Intro to advanced caching in WordPress
Maor Chasen
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019
Balázs Tatár
 
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Balázs Tatár
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
Rebecca Murphey
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Balázs Tatár
 
Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3
makoto tsuyuki
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
Windows Azure Storage & Sql Azure
Windows Azure Storage & Sql AzureWindows Azure Storage & Sql Azure
Windows Azure Storage & Sql Azure
Maarten Balliauw
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
Remy Sharp
 

Viewers also liked (17)

Entropion shar pei
Entropion shar peiEntropion shar pei
Entropion shar pei
Frank FAMOSE
 
Assignment
AssignmentAssignment
Assignment
William Keefe
 
Ardito - Product Stewardship Through Whole Systems Design
Ardito - Product Stewardship Through Whole Systems DesignArdito - Product Stewardship Through Whole Systems Design
Ardito - Product Stewardship Through Whole Systems Design
Environmental Initiative
 
Butlletí El Comú - Núm. 6 - Juny 2016
Butlletí El Comú - Núm. 6 - Juny 2016Butlletí El Comú - Núm. 6 - Juny 2016
Butlletí El Comú - Núm. 6 - Juny 2016
Ajuntament Sant Pere de Ribes
 
Resum sin pasarse de la raya
Resum sin pasarse de la rayaResum sin pasarse de la raya
Resum sin pasarse de la raya
Universitat Autònoma de Barcelona.
 
Penicillins
PenicillinsPenicillins
Penicillins
Jayendra Chaudhary
 
13. u e sound
13. u e sound13. u e sound
13. u e sound
pantiluck
 
Vegetable vocab part 1
Vegetable vocab part 1Vegetable vocab part 1
Vegetable vocab part 1
pantiluck
 
14. oy sound
14. oy  sound14. oy  sound
14. oy sound
pantiluck
 
12. mutiples choices test
12. mutiples choices test12. mutiples choices test
12. mutiples choices test
pantiluck
 
Phonics A e sound 3
Phonics A e sound 3Phonics A e sound 3
Phonics A e sound 3
pantiluck
 
Phonics A e sound 1
Phonics A e sound 1Phonics A e sound 1
Phonics A e sound 1
pantiluck
 
12. vocabulary test Phonics
12. vocabulary test Phonics12. vocabulary test Phonics
12. vocabulary test Phonics
pantiluck
 
6. sh ch sound like don't like
6. sh ch sound like don't like6. sh ch sound like don't like
6. sh ch sound like don't like
pantiluck
 
Keratoconus 2016
Keratoconus 2016Keratoconus 2016
Keratoconus 2016
DINESH and SONALEE
 
Visual Analytics Group 1 Project
Visual Analytics Group 1 ProjectVisual Analytics Group 1 Project
Visual Analytics Group 1 Project
Christy C Langdon
 
Cécité brutale chez un chat
Cécité brutale chez un chatCécité brutale chez un chat
Cécité brutale chez un chat
Frank FAMOSE
 
Entropion shar pei
Entropion shar peiEntropion shar pei
Entropion shar pei
Frank FAMOSE
 
Ardito - Product Stewardship Through Whole Systems Design
Ardito - Product Stewardship Through Whole Systems DesignArdito - Product Stewardship Through Whole Systems Design
Ardito - Product Stewardship Through Whole Systems Design
Environmental Initiative
 
13. u e sound
13. u e sound13. u e sound
13. u e sound
pantiluck
 
Vegetable vocab part 1
Vegetable vocab part 1Vegetable vocab part 1
Vegetable vocab part 1
pantiluck
 
14. oy sound
14. oy  sound14. oy  sound
14. oy sound
pantiluck
 
12. mutiples choices test
12. mutiples choices test12. mutiples choices test
12. mutiples choices test
pantiluck
 
Phonics A e sound 3
Phonics A e sound 3Phonics A e sound 3
Phonics A e sound 3
pantiluck
 
Phonics A e sound 1
Phonics A e sound 1Phonics A e sound 1
Phonics A e sound 1
pantiluck
 
12. vocabulary test Phonics
12. vocabulary test Phonics12. vocabulary test Phonics
12. vocabulary test Phonics
pantiluck
 
6. sh ch sound like don't like
6. sh ch sound like don't like6. sh ch sound like don't like
6. sh ch sound like don't like
pantiluck
 
Visual Analytics Group 1 Project
Visual Analytics Group 1 ProjectVisual Analytics Group 1 Project
Visual Analytics Group 1 Project
Christy C Langdon
 
Cécité brutale chez un chat
Cécité brutale chez un chatCécité brutale chez un chat
Cécité brutale chez un chat
Frank FAMOSE
 
Ad

Similar to jQuery: Tips, tricks and hints for better development and Performance (20)

jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)
Addy Osmani
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
anubavam-techkt
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
chandrashekher786
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
jQuery Performance Tips and Tricks
jQuery Performance Tips and TricksjQuery Performance Tips and Tricks
jQuery Performance Tips and Tricks
Valerii Iatsko
 
jQuery - Doing it right
jQuery - Doing it rightjQuery - Doing it right
jQuery - Doing it right
girish82
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rules
nagarajhubli
 
jQuery performance best practices by Sameera Thilakasiri
jQuery performance best practices by Sameera ThilakasirijQuery performance best practices by Sameera Thilakasiri
jQuery performance best practices by Sameera Thilakasiri
Sameera Thilakasiri
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practices
brinsknaps
 
Bcblackpool jquery tips
Bcblackpool jquery tipsBcblackpool jquery tips
Bcblackpool jquery tips
Jack Franklin
 
J Query - Your First Steps
J Query - Your First StepsJ Query - Your First Steps
J Query - Your First Steps
Bronson Quick
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
Md. Ziaul Haq
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
sergioafp
 
jQuery Tips Tricks Trivia
jQuery Tips Tricks TriviajQuery Tips Tricks Trivia
jQuery Tips Tricks Trivia
Cognizant
 
jQuery Anti-Patterns for Performance
jQuery Anti-Patterns for PerformancejQuery Anti-Patterns for Performance
jQuery Anti-Patterns for Performance
András Kovács
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
Denis Ristic
 
jQuery quick tips
jQuery quick tipsjQuery quick tips
jQuery quick tips
Rochester Oliveira
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
deimos
 
Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3
luckysb16
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
Salvatore Fazio
 
jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)
Addy Osmani
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
anubavam-techkt
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
girish82
 
jQuery Performance Tips and Tricks
jQuery Performance Tips and TricksjQuery Performance Tips and Tricks
jQuery Performance Tips and Tricks
Valerii Iatsko
 
jQuery - Doing it right
jQuery - Doing it rightjQuery - Doing it right
jQuery - Doing it right
girish82
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rules
nagarajhubli
 
jQuery performance best practices by Sameera Thilakasiri
jQuery performance best practices by Sameera ThilakasirijQuery performance best practices by Sameera Thilakasiri
jQuery performance best practices by Sameera Thilakasiri
Sameera Thilakasiri
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practices
brinsknaps
 
Bcblackpool jquery tips
Bcblackpool jquery tipsBcblackpool jquery tips
Bcblackpool jquery tips
Jack Franklin
 
J Query - Your First Steps
J Query - Your First StepsJ Query - Your First Steps
J Query - Your First Steps
Bronson Quick
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
Md. Ziaul Haq
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
sergioafp
 
jQuery Tips Tricks Trivia
jQuery Tips Tricks TriviajQuery Tips Tricks Trivia
jQuery Tips Tricks Trivia
Cognizant
 
jQuery Anti-Patterns for Performance
jQuery Anti-Patterns for PerformancejQuery Anti-Patterns for Performance
jQuery Anti-Patterns for Performance
András Kovács
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
Denis Ristic
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
deimos
 
Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3Learning jquery-in-30-minutes-1195942580702664-3
Learning jquery-in-30-minutes-1195942580702664-3
luckysb16
 
Ad

Recently uploaded (20)

Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Create Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent BuilderCreate Your First AI Agent with UiPath Agent Builder
Create Your First AI Agent with UiPath Agent Builder
DianaGray10
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath InsightsUiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPath Community Berlin: Studio Tips & Tricks and UiPath Insights
UiPathCommunity
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 

jQuery: Tips, tricks and hints for better development and Performance

  • 1. jQueryTips, tricks and hints for better development and performance Jonas De Smet - @glamorous_be - BarcampGhent 2009
  • 2. Who am I ?!
  • 3. Jonas De Smet - 23 years “old” developer - Fan of PHP, jQuery and JSON - Barcamp virgin - Lives in Waregem - Plays rugby with RC Curtrycke - In love with Eline, the girl of his life
  • 4. Why are you here ?!
  • 6. Todays Schedule ✓ What is jQuery? ✓ 10 Usefull tips for better development ✓ 10 Performance tips ✓ Some Q’s & hopefully some A’s
  • 7. What is jQuery? - JavaScript Library - Easy document traversing - Easy event handling - Rapid web development - ... “jQuery is designed to change the way that you write JavaScript” (from jQuery.com)
  • 8. What is jQuery? var elems = document.getElementsByTagName(“p”); for(var i=0;i<elems.length;i++){ if(elems[i].className == “example”){ elems[i].onclick = function(){ alert(“this example doesn’t rocks!”); this.className += “ clicked”; return false; } }
  • 9. What is jQuery? $(“p.example”).click(function(){ $(this).addClass(“clicked”); alert(“this example rocks!”); return false; });
  • 10. Usefull tips for better development
  • 11. Usefull tips - #1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Title of the page</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <script type="text/javascript">document.documentElement.className = 'js';</script> <link rel="stylesheet" href="/style.css" type="text/css" media="screen" /> </head> Avoid flashing content
  • 12. Usefull tips - #2 function testFunction() { console.time(‘test this cool function’); var testString = “”; for(i=0; i<1000; i++) { testString += “item ” + i; } console.timeEnd(‘test this cool function’); } //time will be logged in milliseconds Use Firebug’s console loggings facilities
  • 13. Usefull tips - #3 <script type=”text/javascript” src=”http://www.google.com/jsapi”></script> <script type=”text/javascript”> google.load(“jquery”, “1.3.2”); google.setOnLoadCallback(function() { //init your javascript code }); </script> <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/ jquery.min.js”></script> Load jQuery from Google Code
  • 14. Usefull tips - #4 <div class=”expanded”> <div> <p>Some lorem ipsum</p> <p>Some lorem ipsum</p> <span class=”btn”>Close</span> <span class=”btn”>Close</span> </div> </div> $(“.btn”).click(function() { $(“.btn”).click(function() { var parent = $(this).parent(); var parent = $(this).parent(); if ( parent.hasClass(“expanded”) ) { if ( parent.data(“expanded”) ) { parent.removeClass(“expanded”); parent.data(“expanded”, false); } } else { else { parent.addClass(“expanded”); parent.data(“expanded”, true); } } } } Storing states in classes or even better in .data()
  • 15. Usefull tips - #5 $.expr[“:”]:extlinks = function(element){ var link = $(element).attr(“href ”); var reg = new RegExp('^(?:f|ht)tp(?:s)?://([^/]+)', 'im'); var link_host = (link.match(re) != null) ? link.match(re)[1].toString() : “”; var host = window.location.host; return (link_host != host); } $(“a:extlinks”).attr(“target”,”_blank”); <h3>Some links</h3> <a href=”http://example.com”>Example</a> <a href=”/intern/folder/”>Example</a> Write custom filter selectors
  • 16. Usefull tips - #6 function uglyObject() { //some object stuff } var example = new uglyObject(); $(example).bind(‘addFancy’, function() { // Custom event handling for when the event ‘addFrancy’ is triggered }); $(example).trigger(‘addFancy’); Bind custom events to custom objects
  • 17. Usefull tips - #7 if ($(“div”).length){ //code here } if ($(“div”)[0]){ // code here } // Alternatively $(“div”).get(); $(“div”).get(0); $(“div”).get()[0]; Check if an element exists
  • 18. Usefull tips - #8 // List bound events: console.dir( $(“#elem”).data(“events”) ); // Log ALL handlers for ALL events: $.each($(“#elem”).data(“events”), function(i, event) { jQuery.each(event, function(i, handler){ console.log( handler.toString() ); }); }); // source: http://james.padolsey.com Use jQuery’s event storage
  • 19. Usefull tips - #9 $(“a”).bind(“click.myNamespace”, function() { // Some code for the click event with namespace “myNamespace” }); // Unbind all events with namespace “myNamespace” $(“a”).bind(“click.my2ndNamespace”, function(){ // Some code for the click event with namespace “my2ndNamespace” }); // Unbind events with namespace “myNamespace”, not events with “my2ndNamespace” $(“a”).unbind(“.myNamespace”); $(“#example”).data(“nameValue.aNameSpace”, “teststring”); Namespace your events and stored data
  • 20. Usefull tips - #10 $(“p”).click(somefunction); $(“p span”).click(somefunction); $(“p a”).click(somefunction); // You can do the above easily in one line $(“p, p a, p span”).click(somefunction); Try to group your queries
  • 21. Performance Tips
  • 22. Performance tips - #1 var $specialdiv = $(“#specialdiv”); $specialdiv.filter(function(){ return $(this).hasClass(“clicked”); // Must return a Boolean }); $specialdiv.filter(“.clicked”); var $specialdiv = $(“#specialdiv”); // before var $specialspan = $(“#specialdiv span.on”); // much better var $specialspan = $specialdiv.find(“span.on”); Use .find() or .filter() instead of a new selector
  • 23. Performance tips - #2 1. Use id’s before tags $(“#mydiv”).addClass(“test”); 2. Use tags before classes $(“p”).addClass(“test”); 3. Use classes with a tag $(“p.example”).addClass(“test”);
  • 24. Performance tips - #3 var items = $(“.coolDivs”, $(“#anotherDiv”) ); // or var items = $(“#anotherDiv .coolDivs”); // or even better var items = $(“#anotherDiv div.coolDivs”); //or var items = $(“div.coolDivs”, $(“#anotherDiv”) ); Give selectors a context
  • 25. Performance tips - #4 var $bigInputs = $(“#exampleForm input.big”); $bigInputs.bind(“click”, clickfunction); $bigInputs.addClass(“finished”); // You can define an object in the global scope and access it later window.$myobject = { test: $(“#divWithId”) }; $myobject.test.addClass(“yes”); // Cache added elements to access them later instead of using .live() var $newDiv = $(“<div />”).appendTo(“#anotherDiv”); $newDiv.bind(“click”, clickfunction); Cache jQuery objects and use a $-prefix
  • 26. Performance tips - #5 var $myElement = $(“#element”); $myElement.css(“border”, “1px solid orange”).addClass(“bordered”).fadeIn(“fast”); // another example $myElement.find(“p”).addClass(“yellow”).end().find(“span”).css(“border”,”1px”); // Make you plugins chainable! $.fn.myPlugin = function() { return $(this).addClass(“coolstuff ”); }; Chaining FTW, especially for plugin-development
  • 27. Performance tips - #6 //Wrap everything in one element var $list = $(“#mylist”); var $list = $(“#mylist”); var str = “”; var wrapped = “<ul>”; for (i=0; i < 100; i++) for (i=0; i < 100; i++) { { str += “<li>item “ + i + ”</li>”; wrapped += “<li>item “ + i + ”</li>”; } } $list.html(str); wrapped += “</ul>”; $list.replaceWith(wrapped); Avoid DOM manipulation & keep it to a minimum
  • 28. Performance tips - #7 var $myList = $(“#navigation”); $myList.click(function(evt){ $target = $(evt.target); if($target.is(“li”) ) { doSomethingWhenListItemIsClicked(); } return false; }); // more about jQuery events on http://docs.jquery.com/Events/jQuery.Event Event delegation / bubbling
  • 29. Performance tips - #8 var arr = [ "one", "two", "three", "four", "five" ]; $.each(arr, function() { $("#" + this).text("My id is " + this + "."); }); var arr = [ "one", "two", "three", "four", "five" ]; for ( i=0; i < arr.length; i++ ) { $("#" + i).text("My id is " + i + "."); }); Use a for-loop instead of .each()
  • 30. Performance tips - #9 Use shorthand for $(document).ready() $(function () { // your code }); Use $(window).load() when possible $(window).load( function () { // your code to be excuted when every HTML element is loaded } $(document).ready occurs during page render while objects are downloading $(window).load() event occurs after all objects are called by the HTML
  • 31. Performance tips - #10 Pack and minify your custom scripts (in one) http://javascriptcompressor.com http://dean.edwards.name/packer
  • 32. Q &A
  • 33. Thank you for listening! Twitter @glamorous_be Github http://github.com/glamorous Slideshare http://www.slideshare.net/glamorous LinkedIn http://be.linkedin.com/in/glamorous

Editor's Notes

  • #18: zo ook meer functies beschikbaar: log, debug, warn, info, error
  • #19: 2de methode de voorkeur!
  • #20: jQuery internals =&gt; zo ook removeData() beschikbaar
  • #25: Zeer belangrijk voor plugin development!
  • #26: Zo ook goed te gebruiken bij verschillende events, event samen gaan binden met &amp;#xE9;&amp;#xE9;nzelfde functie als &amp;#x201C;te uit te voeren&amp;#x201D;
  • #29: 1. getElementById 2. getElementsByTagName 3. getElementsByClassName
  • #31: bij aanmaak van nieuwe objecten, cachen =&gt; geen .live() nodig nooit een jQuery selectie herhalen, cache uw objecten!
  • #33: avoid DOM Manipulation (geen .append() maar .html()) eventueel parent node erbij en .replaceWith()
  • #34: geen .live() nodig maar &amp;#xE9;&amp;#xE9;n bind, &amp;#xE9;&amp;#xE9;n event noodzakelijk
  • #36: $(document).ready() wordt uitgevoerd tijdens het downloaden van nog enkele elementen en kan uw pagina &amp;#x201C;ophouden&amp;#x201D;/&amp;#x201D;uitstellen&amp;#x201D; van laden $(window).load() wordt aangeroepen wanneer alle HTML opgeroepen is (zo ook iframes)
  • #37: msh ook combineren van je scripts in &amp;#xE9;&amp;#xE9;n file, eventueel via php de verschillende inladen (denk aan updatebaarheid plugins)