SlideShare a Scribd company logo
1 of 33
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 ?!
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

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, 2018Balá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/2019Balá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 WordPressMaor 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 2019Balá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 2019Balázs Tatár
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code OrganizationRebecca 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, GermanyBalázs Tatár
 
Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3makoto tsuyuki
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery FundamentalsGil Fink
 
Windows Azure Storage & Sql Azure
Windows Azure Storage & Sql AzureWindows Azure Storage & Sql Azure
Windows Azure Storage & Sql AzureMaarten Balliauw
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Remy Sharp
 

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
 
Let's write secure Drupal code!
Let's write secure Drupal code!Let's write secure Drupal code!
Let's write secure Drupal code!
 
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
 
Intro to advanced caching in WordPress
Intro to advanced caching in WordPressIntro to advanced caching in WordPress
Intro to advanced caching in WordPress
 
Jquery introduction
Jquery introductionJquery introduction
Jquery introduction
 
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
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
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
 
Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
 
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
 
jQuery
jQueryjQuery
jQuery
 
Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3Django - 次の一歩 gumiStudy#3
Django - 次の一歩 gumiStudy#3
 
My shell
My shellMy shell
My shell
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
Windows Azure Storage & Sql Azure
Windows Azure Storage & Sql AzureWindows Azure Storage & Sql Azure
Windows Azure Storage & Sql Azure
 
jQuery
jQueryjQuery
jQuery
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
 
Assetic (Zendcon)
Assetic (Zendcon)Assetic (Zendcon)
Assetic (Zendcon)
 

Viewers also liked

Entropion shar pei
Entropion shar peiEntropion shar pei
Entropion shar peiFrank 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 DesignEnvironmental Initiative
 
13. u e sound
13. u e sound13. u e sound
13. u e soundpantiluck
 
Vegetable vocab part 1
Vegetable vocab part 1Vegetable vocab part 1
Vegetable vocab part 1pantiluck
 
14. oy sound
14. oy  sound14. oy  sound
14. oy soundpantiluck
 
12. mutiples choices test
12. mutiples choices test12. mutiples choices test
12. mutiples choices testpantiluck
 
Phonics A e sound 3
Phonics A e sound 3Phonics A e sound 3
Phonics A e sound 3pantiluck
 
Phonics A e sound 1
Phonics A e sound 1Phonics A e sound 1
Phonics A e sound 1pantiluck
 
12. vocabulary test Phonics
12. vocabulary test Phonics12. vocabulary test Phonics
12. vocabulary test Phonicspantiluck
 
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 likepantiluck
 
Visual Analytics Group 1 Project
Visual Analytics Group 1 ProjectVisual Analytics Group 1 Project
Visual Analytics Group 1 ProjectChristy C Langdon
 
Cécité brutale chez un chat
Cécité brutale chez un chatCécité brutale chez un chat
Cécité brutale chez un chatFrank FAMOSE
 

Viewers also liked (17)

Entropion shar pei
Entropion shar peiEntropion shar pei
Entropion shar pei
 
Assignment
AssignmentAssignment
Assignment
 
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
 
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
 
Resum sin pasarse de la raya
Resum sin pasarse de la rayaResum sin pasarse de la raya
Resum sin pasarse de la raya
 
Penicillins
PenicillinsPenicillins
Penicillins
 
13. u e sound
13. u e sound13. u e sound
13. u e sound
 
Vegetable vocab part 1
Vegetable vocab part 1Vegetable vocab part 1
Vegetable vocab part 1
 
14. oy sound
14. oy  sound14. oy  sound
14. oy sound
 
12. mutiples choices test
12. mutiples choices test12. mutiples choices test
12. mutiples choices test
 
Phonics A e sound 3
Phonics A e sound 3Phonics A e sound 3
Phonics A e sound 3
 
Phonics A e sound 1
Phonics A e sound 1Phonics A e sound 1
Phonics A e sound 1
 
12. vocabulary test Phonics
12. vocabulary test Phonics12. vocabulary test Phonics
12. vocabulary test Phonics
 
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
 
Keratoconus 2016
Keratoconus 2016Keratoconus 2016
Keratoconus 2016
 
Visual Analytics Group 1 Project
Visual Analytics Group 1 ProjectVisual Analytics Group 1 Project
Visual Analytics Group 1 Project
 
Cécité brutale chez un chat
Cécité brutale chez un chatCécité brutale chez un chat
Cécité brutale chez un chat
 

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

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 Knowgirish82
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tipsanubavam-techkt
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Jack Franklin
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboardsDenis Ristic
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Thinqloud
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoRob Bontekoe
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practicesbrinsknaps
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 

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

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
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
J query training
J query trainingJ query training
J query training
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Php
PhpPhp
Php
 
Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9
 
JQuery Flot
JQuery FlotJQuery Flot
JQuery Flot
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" Domino
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practices
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

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 ?!
  • 5.
  • 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

  1. zo ook meer functies beschikbaar: log, debug, warn, info, error
  2. 2de methode de voorkeur!
  3. jQuery internals =&gt; zo ook removeData() beschikbaar
  4. Zeer belangrijk voor plugin development!
  5. 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;
  6. 1. getElementById 2. getElementsByTagName 3. getElementsByClassName
  7. bij aanmaak van nieuwe objecten, cachen =&gt; geen .live() nodig nooit een jQuery selectie herhalen, cache uw objecten!
  8. avoid DOM Manipulation (geen .append() maar .html()) eventueel parent node erbij en .replaceWith()
  9. geen .live() nodig maar &amp;#xE9;&amp;#xE9;n bind, &amp;#xE9;&amp;#xE9;n event noodzakelijk
  10. $(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)
  11. msh ook combineren van je scripts in &amp;#xE9;&amp;#xE9;n file, eventueel via php de verschillende inladen (denk aan updatebaarheid plugins)