jQuery Features to Avoid                          Dave Methvin          President, jQuery Foundation                jQuery...
jQuery Is Evolving● There are things in jQuery that ...  ○ make code fragile in large projects  ○ make code hard to unders...
The World of jQuery 1.0
The World of jQuery 1.0● January 2006 browser market share  76% Internet Explorer 5.5 and 6.0  13% Firefox 1.x  11% Others...
Its Gotten Complicated●   Single page applications -- LEAKS!●   Massive amounts of JavaScript●   Script breaks? Page doesn...
What Most Devs Want From jQuery
Temptation to         over   SimplifyWouldnt it be cool if jQuery...● ...automagically figured out what kind of  AJAX/JSON...
Complex APIs Make You Grumpy
jQuery Adapts● Version 1.9 will remove some features  ○ There is a compat plugin (cough, crutch)● Version 2.0 removes supp...
Avoid Deprecated Things!● http://api.jquery.com/category/deprecated/● Ineffective, Inefficient, Inadvisable ...
$.browser● Sniffs around navigator.userAgent string● Easily fooled and fragile● Not future-proof -- bug in this version of...
.toggle(fn1, fn2, fn3 ...)● Cool method, bro● Not really "core" functionality● Lots of caveats in the docs  ○ http://api.j...
jQuery is not JavaScript!
jQuery is not JavaScript!
jQuery is not JavaScript!
Avoid using jQuery...● ...when JavaScript or W3C APIs are  more appropriate and performant● Remember: jQuery is a DOM libr...
Typical Checkbox Handler$("#sameAsBillTo").on("click",   function(){     if ( $(this).is(":checked") ) {       $("#shipTo"...
Use this, not $(this)Instead of $(this) …      Use this!$(this).is(“:checked”)    this.checked$(this).prop(“checked”)   th...
Use this, not $(this)Instead of $(this) …      Use this!$(this).is(“:checked”)    this.checked$(this).prop(“checked”)   th...
Better Checkbox Handler$("#sameAsBillTo").on("click", function(){   $("#shipTo").toggle(!this.checked); });
Use W3C CSS SelectorsSelector extension     Use this (W3C CSS):checkbox, :radio, :   input[type=X]text, :image, :file, :re...
Even More Stuff To Avoid...●   Features we cant remove●   Too frequently and commonly used●   Sometimes cute, but theyll b...
How Every Project Starts
What Every Project Becomes
$(html, props)● You can say:  $("<p />")     .attr("class", "active")     .click(myClickHandler)     .text("Hello world") ...
$(html, props) Pitfalls 1● If the name is a method, its called with  the (single) argument you provide:  $("<input />", { ...
$(html, props) Pitfalls 2● Methods can collide with attributes!  $("<input />", {    type: "text",    size: "15" // uh-oh!...
Action at a Distance
jQuery.ajaxOptions()● Lets you change behavior of $.ajax()● GLOBALLY● Including any third-party plugins● Most jQuery code ...
What does this do?   $.ajax({     url: "file.txt",     success: function(data){       alert(data);     }   });
How I Hosed Your AJAX  $.ajaxSetup({    type: "POST",    dataType: "json",    timeout: 500 // ms!  });
Avoiding Ajax AnnihilationMake your own $.ajax() wrapper:  function jsonRequest(options)  {    return $.ajax(       $.exte...
Using $() to create HTML● jQuery(), aka $(), accepts anything!  ○   function (for document ready)  ○   DOM element  ○   Ar...
Using $() to create HTML● jQuery(), aka $(), accepts anything!  ○   function (for document ready)  ○   DOM element  ○   Ar...
The "Looks Like HTML" Rule
The "Looks Like HTML" Rule"If a string is passed as the parameter to$(), jQuery examines the string to see if itlooks like...
Some people, when confrontedwith a problem, think "I know,Ill use regular expressions."Now they have two problems.        ...
Cross site scripting (XSS)● $() can run <script>s in HTML● $() can set HTML inline event handlers● Many sites use unvalida...
Rule Change for jQuery 1.9● A string will only "look like HTML" if it  starts with a "<" character!● Leading whitespace al...
Selector or HTML in 1.7?1)   "<p>Hello</p>" HTML2)   "Hello<p>there</p> world!" HTML3)   ".tip[title=Hello]" selector4)   ...
Selector or HTML in 1.9?1)    "<p>Hello</p>" HTML2)    "Hello<p>there</p> world!" selector3)    ".tip[title=Hello]" select...
Say what you want!● In jQuery 1.8:  ○ $.parseHTML(html, runScripts)     ■ html is a string of arbitrary HTML     ■ runScri...
jQuerys Not Perfect●   Use the good parts●   Avoid the bad parts●   Youll be happier with jQuery●   Your co-workers will t...
Questions? Twitter:  @davemethvin Github:  dmethvin IRC #jquery-dev:   DaveMethvin
jQuery Features to Avoid
jQuery Features to Avoid
Upcoming SlideShare
Loading in...5
×

jQuery Features to Avoid

942

Published on

jQuery 1.9 will be cleaning up the library's API, but even so there are still features that should be used with care--or avoided completely.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
942
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
4
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "jQuery Features to Avoid"

  1. 1. jQuery Features to Avoid Dave Methvin President, jQuery Foundation jQuery Core Team Lead
  2. 2. jQuery Is Evolving● There are things in jQuery that ... ○ make code fragile in large projects ○ make code hard to understand ○ make code SLOW● ... so you should avoid them!But how did this happen?
  3. 3. The World of jQuery 1.0
  4. 4. The World of jQuery 1.0● January 2006 browser market share 76% Internet Explorer 5.5 and 6.0 13% Firefox 1.x 11% Others (Netscape, AOL)● State of web development in 2006 ○ HTML4, EcmaScript 3 (IE5 lacked try-catch) ○ AJAX term just coined in February 2005 ○ Nearly all pages were full-reload design ○ JavaScript was generally non-essential
  5. 5. Its Gotten Complicated● Single page applications -- LEAKS!● Massive amounts of JavaScript● Script breaks? Page doesnt work.● MORE browsers and screen sizes! ○ IE6-10, Firefox 3.6-15, Chrome 20-22, Safari 3-6, plus mobile browser variants (Android, iPhone/iPod, BlackBerry) which are often old and never updated! Bonus: IE9 on Xbox!
  6. 6. What Most Devs Want From jQuery
  7. 7. Temptation to over SimplifyWouldnt it be cool if jQuery...● ...automagically figured out what kind of AJAX/JSONP request to make and did the "right thing" with the response?● Its wonderful when it works● Hard to debug when it doesnt● Crazy hard to document
  8. 8. Complex APIs Make You Grumpy
  9. 9. jQuery Adapts● Version 1.9 will remove some features ○ There is a compat plugin (cough, crutch)● Version 2.0 removes support for IE 6/7/8● We will maintain both 1.9 and 2.0 and the APIs will be compatible Result? ● Smaller size ● Better performance ● Fewer "trip hazards"
  10. 10. Avoid Deprecated Things!● http://api.jquery.com/category/deprecated/● Ineffective, Inefficient, Inadvisable ...
  11. 11. $.browser● Sniffs around navigator.userAgent string● Easily fooled and fragile● Not future-proof -- bug in this version of Chrome or IE is no guarantee of bug in future Chrome or IE!● Usually you want to feature detect● Modernizr!
  12. 12. .toggle(fn1, fn2, fn3 ...)● Cool method, bro● Not really "core" functionality● Lots of caveats in the docs ○ http://api.jquery.com/toggle-event/ ○ "Practically reads like a suicide note"
  13. 13. jQuery is not JavaScript!
  14. 14. jQuery is not JavaScript!
  15. 15. jQuery is not JavaScript!
  16. 16. Avoid using jQuery...● ...when JavaScript or W3C APIs are more appropriate and performant● Remember: jQuery is a DOM library● All of JavaScript is yours to command● jQuery tries to avoid getting in your way
  17. 17. Typical Checkbox Handler$("#sameAsBillTo").on("click", function(){ if ( $(this).is(":checked") ) { $("#shipTo").hide(); } else { $("#shipTo").show(); } });
  18. 18. Use this, not $(this)Instead of $(this) … Use this!$(this).is(“:checked”) this.checked$(this).prop(“checked”) this.checked$(this).is(“:disabled”) this.disabled$(this).attr(“id”) this.id$(this).attr(“class”) this.className
  19. 19. Use this, not $(this)Instead of $(this) … Use this!$(this).is(“:checked”) this.checked$(this).prop(“checked”) this.checked$(this).is(“:disabled”) this.disabled$(this).attr(“id”) this.id$(this).attr(“class”) this.className Up to 100 times faster!
  20. 20. Better Checkbox Handler$("#sameAsBillTo").on("click", function(){ $("#shipTo").toggle(!this.checked); });
  21. 21. Use W3C CSS SelectorsSelector extension Use this (W3C CSS):checkbox, :radio, : input[type=X]text, :image, :file, :reset:button button, input[type=button]:header h1, h2, h3, h4, h5:first :first-child or .first():last :last-child or .last()
  22. 22. Even More Stuff To Avoid...● Features we cant remove● Too frequently and commonly used● Sometimes cute, but theyll bite you● Especially bad on large projects
  23. 23. How Every Project Starts
  24. 24. What Every Project Becomes
  25. 25. $(html, props)● You can say: $("<p />") .attr("class", "active") .click(myClickHandler) .text("Hello world") .appendTo("body");● Or, using $(html, props): $("<p />", { "class": "active", click: myClickHandler, text: "Hello world" }).appendTo("body");
  26. 26. $(html, props) Pitfalls 1● If the name is a method, its called with the (single) argument you provide: $("<input />", { type: "checkbox", prop: { checked: true } }).appendTo("body");● No method with that name? It will be set as an attribute!
  27. 27. $(html, props) Pitfalls 2● Methods can collide with attributes! $("<input />", { type: "text", size: "15" // uh-oh! $.fn.size() attr: { size: 15 } // works }).appendTo("body");● This can happen with plugins someone adds to the project at a later time
  28. 28. Action at a Distance
  29. 29. jQuery.ajaxOptions()● Lets you change behavior of $.ajax()● GLOBALLY● Including any third-party plugins● Most jQuery code expects the "normal" defaults that are documented by the API
  30. 30. What does this do? $.ajax({ url: "file.txt", success: function(data){ alert(data); } });
  31. 31. How I Hosed Your AJAX $.ajaxSetup({ type: "POST", dataType: "json", timeout: 500 // ms! });
  32. 32. Avoiding Ajax AnnihilationMake your own $.ajax() wrapper: function jsonRequest(options) { return $.ajax( $.extend({ dataType: "json", ... }, options) ); }
  33. 33. Using $() to create HTML● jQuery(), aka $(), accepts anything! ○ function (for document ready) ○ DOM element ○ Array of DOM elements ○ A plain JavaScript object ○ HTML element string and props (as we saw) ○ Arbitrary HTML string ○ Selector string and context
  34. 34. Using $() to create HTML● jQuery(), aka $(), accepts anything! ○ function (for document ready) ○ DOM element ○ Array of DOM elements ○ A plain JavaScript object ○ HTML element string and props (as we saw) ○ Arbitrary HTML string ○ Selector string and context
  35. 35. The "Looks Like HTML" Rule
  36. 36. The "Looks Like HTML" Rule"If a string is passed as the parameter to$(), jQuery examines the string to see if itlooks like HTML (i.e., it has <tag...>somewhere within the string). If not, thestring is interpreted as a selectorexpression ..." -- http://api.jquery.com/jQuery/#jQuery2
  37. 37. Some people, when confrontedwith a problem, think "I know,Ill use regular expressions."Now they have two problems. -- Jamie Zawinski
  38. 38. Cross site scripting (XSS)● $() can run <script>s in HTML● $() can set HTML inline event handlers● Many sites use unvalidated input to $() ○ "http://mysite.com/page.html#someid" ○ $(window.location.hash) // #someid ○ Uh oh! ■ http://jsfiddle.net/dmethvin/uKYUP/
  39. 39. Rule Change for jQuery 1.9● A string will only "look like HTML" if it starts with a "<" character!● Leading whitespace allowed? Maybe.● Helps to prevent inadvertent script interpretation in HTML● Developers still must validate input!
  40. 40. Selector or HTML in 1.7?1) "<p>Hello</p>" HTML2) "Hello<p>there</p> world!" HTML3) ".tip[title=Hello]" selector4) ".tip[title=<b>Hello</b>]" HTML5) "#footer .copyright" selector6) "#ONE <b>Redskins</b> fan!" HTML
  41. 41. Selector or HTML in 1.9?1) "<p>Hello</p>" HTML2) "Hello<p>there</p> world!" selector3) ".tip[title=Hello]" selector4) ".tip[title=<b>Hello</b>]" selector5) "#footer .copyright" selector6) "#ONE <b>Redskins</b> fan!" selector Note that many of these are NOT valid CSS selectors and will throw an error.
  42. 42. Say what you want!● In jQuery 1.8: ○ $.parseHTML(html, runScripts) ■ html is a string of arbitrary HTML ■ runScripts is a Boolean that says whether to run inline or external scripts in the HTML; defaults to false.● Not a panacea for all XSS problems ○ http://jsfiddle.net/dmethvin/VNBDF/● Needs documentation...sorry!
  43. 43. jQuerys Not Perfect● Use the good parts● Avoid the bad parts● Youll be happier with jQuery● Your co-workers will thank you! You can find this presentation at: http://slideshare.net/
  44. 44. Questions? Twitter: @davemethvin Github: dmethvin IRC #jquery-dev: DaveMethvin
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×