jquery features to avoid

46
jQuery Features to Avoid Dave Methvin President, jQuery Foundation jQuery Core Team Lead

Upload: dmethvin

Post on 10-May-2015

876 views

Category:

Technology


0 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: jQuery Features to Avoid

jQuery Features to AvoidDave Methvin

President, jQuery FoundationjQuery Core Team Lead

Page 2: jQuery Features to Avoid

● 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?

jQuery Is Evolving

Page 3: jQuery Features to Avoid

The World of jQuery 1.0

Page 4: jQuery Features to Avoid

● January 2006 browser market share76% Internet Explorer 5.5 and 6.013% Firefox 1.x11% 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

The World of jQuery 1.0

Page 5: jQuery Features to Avoid
Page 6: jQuery Features to Avoid

● Single page applications -- LEAKS!● Massive amounts of JavaScript● Script breaks? Page doesn't 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!

It's Gotten Complicated

Page 7: jQuery Features to Avoid

What Most Devs Want From jQuery

Page 8: jQuery Features to Avoid

Wouldn't it be cool if jQuery...● ...automagically figured out what kind of

AJAX/JSONP request to make and did the "right thing" with the response?

● It's wonderful when it works● Hard to debug when it doesn't● Crazy hard to document

Temptation to over Simplify

Page 9: jQuery Features to Avoid

Complex APIs Make You Grumpy

Page 10: jQuery Features to Avoid

● 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 compatibleResult?

● Smaller size ● Better performance● Fewer "trip hazards"

jQuery Adapts

Page 11: jQuery Features to Avoid

● http://api.jquery.com/category/deprecated/● Ineffective, Inefficient, Inadvisable ...

Avoid Deprecated Things!

Page 12: jQuery Features to Avoid

● 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!

$.browser

Page 13: jQuery Features to Avoid

● 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"

.toggle(fn1, fn2, fn3 ...)

Page 14: jQuery Features to Avoid

jQuery is not JavaScript!

Page 15: jQuery Features to Avoid

jQuery is not JavaScript!

Page 16: jQuery Features to Avoid

jQuery is not JavaScript!

Page 17: jQuery Features to Avoid

● ...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

Avoid using jQuery...

Page 18: jQuery Features to Avoid

$("#sameAsBillTo").on("click",function(){ if ( $(this).is(":checked") ) {

$("#shipTo").hide();} else {

$("#shipTo").show(); }}

);

Typical Checkbox Handler

Page 19: jQuery Features to Avoid

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

Page 20: jQuery Features to Avoid

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!

Page 21: jQuery Features to Avoid

$("#sameAsBillTo").on("click", function(){ $("#shipTo").toggle(!this.checked); });

Better Checkbox Handler

Page 22: jQuery Features to Avoid

Use W3C CSS SelectorsSelector extension Use this (W3C CSS)

:checkbox, :radio, :

text, :image, :file, :

reset

input[type=X]

:button button, input[type=button]

:header h1, h2, h3, h4, h5

:first :first-child or .first()

:last :last-child or .last()

Page 23: jQuery Features to Avoid
Page 24: jQuery Features to Avoid

● Features we can't remove● Too frequently and commonly used● Sometimes cute, but they'll bite you● Especially bad on large projects

Even More Stuff To Avoid...

Page 25: jQuery Features to Avoid

How Every Project Starts

Page 26: jQuery Features to Avoid

What Every Project Becomes

Page 27: jQuery Features to Avoid

● 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");

$(html, props)

Page 28: jQuery Features to Avoid

● If the name is a method, it's 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!

$(html, props) Pitfalls 1

Page 29: jQuery Features to Avoid

● 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

$(html, props) Pitfalls 2

Page 30: jQuery Features to Avoid

Action at a Distance

Page 31: jQuery Features to Avoid

● Lets you change behavior of $.ajax()

● G L O B A L L Y● Including any third-party plugins● Most jQuery code expects the "normal"

defaults that are documented by the API

jQuery.ajaxOptions()

Page 32: jQuery Features to Avoid

$.ajax({url: "file.txt",success: function(data){alert(data);

}});

What does this do?

Page 33: jQuery Features to Avoid

$.ajaxSetup({type: "POST",dataType: "json",timeout: 500 // ms!

});

How I Hosed Your AJAX

Page 34: jQuery Features to Avoid

Make your own $.ajax() wrapper:function jsonRequest(options){ return $.ajax( $.extend({

dataType: "json", ...

}, options) );}

Avoiding Ajax Annihilation

Page 35: jQuery Features to Avoid

● 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

Using $() to create HTML

Page 36: jQuery Features to Avoid

● 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

Using $() to create HTML

Page 37: jQuery Features to Avoid

The "Looks Like HTML" Rule

Page 38: jQuery Features to Avoid

"If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it has <tag...> somewhere within the string). If not, the string is interpreted as a selector expression ..."

-- http://api.jquery.com/jQuery/#jQuery2

The "Looks Like HTML" Rule

Page 39: jQuery Features to Avoid

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

-- Jamie Zawinski

Page 40: jQuery Features to Avoid

● $() 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/

Cross site scripting (XSS)

Page 41: jQuery Features to Avoid

● 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!

Rule Change for jQuery 1.9

Page 42: jQuery Features to Avoid

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

Selector or HTML in 1.7?

Page 43: jQuery Features to Avoid

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.

Selector or HTML in 1.9?

Page 44: jQuery Features to Avoid

● 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!

Say what you want!

Page 45: jQuery Features to Avoid

● Use the good parts● Avoid the bad parts● You'll be happier with jQuery● Your co-workers will thank you!

You can find this presentation at:

http://slideshare.net/

jQuery's Not Perfect

Page 46: jQuery Features to Avoid

Twitter: @davemethvin

Github: dmethvin

IRC #jquery-dev: DaveMethvin

Questions?