The document discusses various jQuery anti-patterns that can negatively impact performance and compression, and provides recommendations to improve them. It covers caching DOM selections and length, using document fragments to append content, leveraging event delegation, minimizing DOM touches, and optimizing selectors. It also discusses mangling variable names and using compression tools like YUI Compressor to reduce file size.
The magic of jQuery's CSS-based selection makes it easy to think about our code in terms of the DOM, and sometimes that approach is exactly right. Other times, though, what we're trying to accomplish is only tangentially related to our nodes, and opting for an approach where we think in terms of functionality -- not how that functionality is manifested on our page -- can pay big dividends in terms of flexibility. In this talk, we'll look at a small sample application where the DOM takes a back seat to functionality-focused modules, and see how the approach can change the way we write and organize our code.
When you move beyond adding simple enhancements to your website with jQuery and start building full-blown client-side applications, how do you organize your code? At this month's Triangle JS Meetup, we'll take a look at patterns for application development using jQuery that promote the principles of tight encapsulation and loose coupling, including classes, the publish/subscribe paradigm, and dependency management and build systems.
The jQuery community has provided thousands of useful plugins which can be stitched together to create exceptional websites. However, organizing those plugins, tracking their upstream changes and managing dependencies can become a nightmare with a system to help you manage. JavascriptMVC, and specifically its new version 3 release, provides a framework for organizing outside code, integrating it into your workflow and compressing down to a single output javascript file. This talk will focus on taking external plugins such as jQuery Tools, jQuery UI and other popular plugins and creating a workflow for building larger applications from these components. I will show how to use the JavascriptMVC “getter” and “pluginify” scripts to pull external resources. With JavascriptMVC 3, css and javascript can be packaged together creating truly convenient widgets. I will also demonstrate how often-used pieces of functionality can be abstracted into plugins and shared with the general community via Github.
JavaScript - Like a Box of Chocolates - jsDayRobert Nyman
This presentation aims to give you information about the JavaScript language itself; pros, cons and pitfalls. It will cover the basics and then go into objects, scope, closure and some performance bits.
The magic of jQuery's CSS-based selection makes it easy to think about our code in terms of the DOM, and sometimes that approach is exactly right. Other times, though, what we're trying to accomplish is only tangentially related to our nodes, and opting for an approach where we think in terms of functionality -- not how that functionality is manifested on our page -- can pay big dividends in terms of flexibility. In this talk, we'll look at a small sample application where the DOM takes a back seat to functionality-focused modules, and see how the approach can change the way we write and organize our code.
When you move beyond adding simple enhancements to your website with jQuery and start building full-blown client-side applications, how do you organize your code? At this month's Triangle JS Meetup, we'll take a look at patterns for application development using jQuery that promote the principles of tight encapsulation and loose coupling, including classes, the publish/subscribe paradigm, and dependency management and build systems.
The jQuery community has provided thousands of useful plugins which can be stitched together to create exceptional websites. However, organizing those plugins, tracking their upstream changes and managing dependencies can become a nightmare with a system to help you manage. JavascriptMVC, and specifically its new version 3 release, provides a framework for organizing outside code, integrating it into your workflow and compressing down to a single output javascript file. This talk will focus on taking external plugins such as jQuery Tools, jQuery UI and other popular plugins and creating a workflow for building larger applications from these components. I will show how to use the JavascriptMVC “getter” and “pluginify” scripts to pull external resources. With JavascriptMVC 3, css and javascript can be packaged together creating truly convenient widgets. I will also demonstrate how often-used pieces of functionality can be abstracted into plugins and shared with the general community via Github.
JavaScript - Like a Box of Chocolates - jsDayRobert Nyman
This presentation aims to give you information about the JavaScript language itself; pros, cons and pitfalls. It will cover the basics and then go into objects, scope, closure and some performance bits.
When you move beyond simple snippets of jQuery and start developing more complex interactions, your code can quickly become unwieldy and difficult to debug and maintain. In this presentation, I outline an object-based approach to organizing your jQuery.
jQuery is drawing newcomers to JavaSCript in droves. As a community, we have an obligation -- and it is in our interest -- to help these newcomers understand where jQuery ends and JavaScript begins.
An introduction to jQuery. How to access elements, what you can then do with them, how to create elements, a bit of AJAX and some JSON. Given as a lecture in the fh ooe in Hagenberg, Austria in December 2011.
Front-end Javascript testing is a thing since 3/4 years now, but it’s still a ghost in the dev community: someone believes in it while someone else is not convinced at all.
This talk will tackle the misconceptions about testing, how and what to test, dependencies mocking and strategies to write tests in a profitable way without being afraid.
Using Templates to Achieve Awesomer ArchitectureGarann Means
Templates are the best kind of tool: simple to write and implement, but powerful enough to make your architecture slicker and your code leaner. Getting markup out of your Javascript is a huge deal, but templates can help with more than that. They can manage repeated code snippets, allow you to deftly switch states in single page applications, and help keep your code DRY when supporting users with and without Javascript enabled. Using and extending them creatively can make any architecture a little awesomer.
Things you should know about jQuery JavaScript library. A JavaScript library designed to hide painful cross-browser compatibility issues while presenting a solid, usable, API.
You’ve seen Kris’ open source libraries, but how does he tackle coding out an application? Walk through green fields with a Symfony expert as he takes his latest “next big thing” idea from the first line of code to a functional prototype. Learn design patterns and principles to guide your way in organizing your own code and take home some practical examples to kickstart your next project.
Drupal is Stupid (But I Love It Anyway)brockboland
Regrettably, my machine didn't cooperate when I tried to record this presentation. I don't think the slides will do you much good without the stuff I said, but a few people asked for them.
---
Depending on who you ask, Drupal is either a framework or a platform, but no matter how you look at it, there are things about it that suck. Hear Brock Boland talk about the pain points of coding for Drupal 6, how things have improved in Drupal 7, and what's expected to be better in Drupal 8.
This course will give you the knowledge you need to properly and effectively start integrating jQuery, the popular JavaScript library, into your web development projects. Over the course of two days, you'll learn the fundamental concepts of JavaScript and jQuery and tackle real-world exercises to solidify your understanding of the language and the library. This class is aimed at beginning jQuery users, although intermediate users may also benefit from the more formalized introduction to the library this class will offer.
If you have used Facebook's React library, then you are familiar with the concept of application state. React components are, at their core (and as noted in the official documentation), simple state machines. This declarative approach to building a UI may take some adjusting to, but it ultimately simplifies kludgy imperative code into smaller, much more manageable pieces.
This pattern of manipulating state and responding to those changes can be implemented to great effect using the Symfony Event Dispatcher. This talk will step through this state-based approach to building an easily maintained and testable PHP application, tease out a few gotchas, and share real-world applications.
My talk at the Yahoo! Frontend Engineering Summit in December 2007. It explains how you can embed the YUI component by component on demand rather than in one big chunk.
When you move beyond simple snippets of jQuery and start developing more complex interactions, your code can quickly become unwieldy and difficult to debug and maintain. In this presentation, I outline an object-based approach to organizing your jQuery.
jQuery is drawing newcomers to JavaSCript in droves. As a community, we have an obligation -- and it is in our interest -- to help these newcomers understand where jQuery ends and JavaScript begins.
An introduction to jQuery. How to access elements, what you can then do with them, how to create elements, a bit of AJAX and some JSON. Given as a lecture in the fh ooe in Hagenberg, Austria in December 2011.
Front-end Javascript testing is a thing since 3/4 years now, but it’s still a ghost in the dev community: someone believes in it while someone else is not convinced at all.
This talk will tackle the misconceptions about testing, how and what to test, dependencies mocking and strategies to write tests in a profitable way without being afraid.
Using Templates to Achieve Awesomer ArchitectureGarann Means
Templates are the best kind of tool: simple to write and implement, but powerful enough to make your architecture slicker and your code leaner. Getting markup out of your Javascript is a huge deal, but templates can help with more than that. They can manage repeated code snippets, allow you to deftly switch states in single page applications, and help keep your code DRY when supporting users with and without Javascript enabled. Using and extending them creatively can make any architecture a little awesomer.
Things you should know about jQuery JavaScript library. A JavaScript library designed to hide painful cross-browser compatibility issues while presenting a solid, usable, API.
You’ve seen Kris’ open source libraries, but how does he tackle coding out an application? Walk through green fields with a Symfony expert as he takes his latest “next big thing” idea from the first line of code to a functional prototype. Learn design patterns and principles to guide your way in organizing your own code and take home some practical examples to kickstart your next project.
Drupal is Stupid (But I Love It Anyway)brockboland
Regrettably, my machine didn't cooperate when I tried to record this presentation. I don't think the slides will do you much good without the stuff I said, but a few people asked for them.
---
Depending on who you ask, Drupal is either a framework or a platform, but no matter how you look at it, there are things about it that suck. Hear Brock Boland talk about the pain points of coding for Drupal 6, how things have improved in Drupal 7, and what's expected to be better in Drupal 8.
This course will give you the knowledge you need to properly and effectively start integrating jQuery, the popular JavaScript library, into your web development projects. Over the course of two days, you'll learn the fundamental concepts of JavaScript and jQuery and tackle real-world exercises to solidify your understanding of the language and the library. This class is aimed at beginning jQuery users, although intermediate users may also benefit from the more formalized introduction to the library this class will offer.
If you have used Facebook's React library, then you are familiar with the concept of application state. React components are, at their core (and as noted in the official documentation), simple state machines. This declarative approach to building a UI may take some adjusting to, but it ultimately simplifies kludgy imperative code into smaller, much more manageable pieces.
This pattern of manipulating state and responding to those changes can be implemented to great effect using the Symfony Event Dispatcher. This talk will step through this state-based approach to building an easily maintained and testable PHP application, tease out a few gotchas, and share real-world applications.
My talk at the Yahoo! Frontend Engineering Summit in December 2007. It explains how you can embed the YUI component by component on demand rather than in one big chunk.
Investors have had to contend with many upsetting concerns over the last year, including geopolitical uncertainty, social unrest, natural disasters, monetary tightening, new regulations, and a U.S. government downgrade. The European Sovereign Debt Crisis was underway for over a year when the worrying Nightmares began compounding in March 2011. These Nightmares have undercut confidence and global growth expectations, which impeded equity returns and drove Treasury yields lower. Uncertainty fueled much higher volatility across equity, bond, currency, and commodity markets. Relative valuations across asset classes now provide compelling opportunities for active management, as extreme relative valuations should normalize. U.S. equity valuations are compelling enough, in our opinion, to support a U.S. equity return exceeding 9.5%.
Surprising strength in earnings, consumption, and investment activity has persisted. Earnings growth and high profit margins have benefited from above average productivity, but earnings growth is expected to slow this year to 10%, according to the consensus. The “output gapers” have argued that there is too much slack in employment and manufacturing capacity to push up inflation, yet consumer prices surged 3.9% before easing recently. Normalizing inflation and growth will increase pressure to raise interest rates.
Lear more at http://www.nafcu.org/nifcus
This presentation includes the ILC-UK's Ben Franklin and Cesira Urzì Brancati presenting a summary of the Moved to Care report; a response from Dr Shereen Hussein, Senior Research Fellow at King's College London; and a response from Madeleine Sumption, Director of the Migration Observatory.
The biggest way to make your email campaign more profitable is conversion. 7 of the easiest ways to do that are to write to one person, write consistently, write stronger subject lines, test the length of your email copy, add stores to your email copy, focus on one response per email, and create sequences. In the article we will go over all seven of these and explain how they relate to your email conversion, and eventually, raise your profits.
Exploring patterns of expenditure among older people and what explains theseILC- UK
A presentation given by David Hayes and Andrea Finney of the Personal Finance Research Centre at the University of Bristol. Findings from a joint ILC-UK/PFRC project, on Financial dimensions of well-being in older age funded by ESRC.
Lead Generation Content For Advisors: 13 Tax Tips For Doctors For 2013Advisors4Advisors
You can purchase this special report targeted to doctors branded with your logo. Post it for all to see on your website, or require visitors submit their contact information to view the report in order to generate leads.
Last year, AOL adopted a new content strategy and has positioned itself as a premier destination for original content. Core to this strategy is having reusable, highly efficient and optimized common code and experiences at scale, which is where jQuery comes in. Check in with Dave Artz to see how jQuery has helped his front-end standards team tackle unique challenges like optimizing 3rd party widget performance, overriding plugin functionality, and managing dependencies and updates across 100+ sites spanning multiple back-end platforms.
Leverage patterns of large-scale JS – such as modules, publish-subscribe and delegation – to achieve extreme performance without sacrificing maintainability.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
3. Me.
Interaction Designer at Molecular, Inc.
jQuery Team Member - Dev. Relations
@paul_irish
http://paulirish.com Front-end development blog
http://aurgasm.us Eclectic music blog
15. Architecture - Object Literal
Advantages:
Easier to navigate and discuss
Profilers give you actual names to work with
You can execute these from firebug console
You can write unit tests against them
16. Anti-Pattern: The requery
// create and append your element
$(document.body).append("<div class='baaron'/>");
// requery to bind stuff
$("div.baaron").click(function(){});
// better:
// swap to appendTo to hold your elem
$("<div class='baaron'/>")
.appendTo(document.body)
.click(function(){});
18. This is not the .context property
// find all stylesheets in the body
var bodySheets = $('style',document.body);
bodySheets.context // ==> BODY element
Ignore that for the moment, I know no one that’s
found a use
19. $(‘#whats .the’,context)
Never pass it a selector string. Ever.
No performance gain vs $(root).find(selector)
var arms = $('div.robotarm', '#container');
// instead do:
var arms = $('#container').find('div.robotarm');
20. $(‘#whats .the’,context)
You typically pass it this, but it’s purely a
convenience to avoid find()
$('form.comments',this).submit(captureSubmit);
// exact same as
$(this).find('form.comments').submit(captureSubmit);
Which is more readable?
$('.reply_form', $(this).closest('.comment')).hide();
$(this).closest('.comment').find('.reply_form').hide();
22. Come on, my selector
Selector engines have come a long, long way.
23. Come on, my selector
Selector engines have come a long, long way.
24. Come on, my selector
Engines work in different ways
Top-down, bottom-up, function creation, other crazy shit
// from NWMatcher:
// selecting '.outmost #outer span'
T=e.nodeName;if(T=="SPAN"||T=="span")
{while((e=e.parentNode)&&e.nodeType==1)
{if((n=e.getAttributeNode("id"))&&n.value=="outer")
{if((e=e.parentNode)&&e.nodeType==1)
{C=e.className;if(C&&(" "+C+" ").indexOf(" outmost ")>-1)
{r[X++]=N;continue main;}}}}}
25. Selector engines, parse direction
Left to right (Top-down) Right to left (Bottom-up)
Mootools Sizzle
Sly YUI 3
Peppy NWMatcher
Dojo Acme
Ext JS
Prototype.js
details: http://alexsexton.com/selectors/
26. Selector engines, parse direction
div.data table.attendees .gonzalez
Left to right (Top-down) Right to left (Bottom-up)
Mootools Sizzle
Sly YUI 3
Peppy NWMatcher
Dojo Acme
Ext JS
Prototype.js
details: http://alexsexton.com/selectors/
27. Selector engines, parse direction
Left to right (Top-down) Right to left (Bottom-up)
Mootools Sizzle
Sly YUI 3
Peppy NWMatcher
Dojo Acme
Ext JS
Prototype.js
details: http://alexsexton.com/selectors/
28. Selector engines, parse direction
Left to right (Top-down) Right to left (Bottom-up)
Mootools Sizzle
Sly YUI 3
Peppy NWMatcher
Dojo Acme querySelectorAll (qSA)
Ext JS
Prototype.js
details: http://alexsexton.com/selectors/
29. Selector Optimization
Specific on the right, light on the left
// let's find scott
div.data .gonzalez
// specific on right, light on the left
.data td.gonzalez
tag.class if possible on your right-most selector.
just tag or just .class on left.
30. Selector Optimization
Of course, descending from an #id is best
// basic #id-based selector
var arms = $('#container div.robotarm');
// hyper-optimized #id case first, then find:
var arms = $('#container').find('div.robotarm');
31. Selector Optimization
Don’t be needlessly specific
// let's find scott
.data table.attendees td.gonzalez
// better: drop the middle
.data td.gonzalez
A flatter DOM helps, so move to HTML5
Also a wider range of tags speeds up filters
32. Selector Optimization
Avoid the universal selector
Avoid the implied universal selector
$('.buttons > *') // terribly costly
$('.buttons').children() // much better
$('.gender :radio') // implied universal
$('.gender *:radio') // exact same, explicit now
$('.gender input:radio') // much better
34. Event Delegation
function delegate(type, delegate, handler) {
return $(document).bind(type, function(event) {
var target = $(event.target);
if (target.is(delegate)) {
return handler.apply(target, arguments);
}
});
}
delegate('click','td.jehl',createRockstar);
// and with live():
$('td.jehl').live('click',createRockstar);
35. Event Delegation
live() isn’t just for dynamic content
Speeds up page load
Only one event handler is bound vs many
Good for >3 elements all getting the same handler
// using live(), skipping selection on load
var jqElem = $(document);
jqElem.selector = 'li.ui';
jqElem.live('dblclick', dblhandler);
36. Event Delegation
live() isn’t just for dynamic content
Speeds up page load
Only one event handler is bound vs many
Good for >3 elements all getting the same handler
// using live(), skipping selection on load
var jqElem = $(document);
jqElem.selector = 'li.ui';
jqElem.live('dblclick', dblhandler);
37. Event Delegation
delegate() bakes in huge performance gains
explicit context reduces overhead by ~80%
Use it instead of live() if possible
// awkward but equivalent
$('a.trigger',$('#container')[0]).live('click',handlerFn)
// so damn fine
$('#container').delegate('click','a.trigger',handlerFn)
38. Event Delegation new
1.4 in
.2!
delegate() bakes in huge performance gains
explicit context reduces overhead by ~80%
Use it instead of live() if possible
// awkward but equivalent
$('a.trigger',$('#container')[0]).live('click',handlerFn)
// so damn fine
$('#container').delegate('click','a.trigger',handlerFn)
39. The DOM is slow
Pull elements off the DOM while you toy with them
var table = $('#some-table');
var parent = table.parent();
table.detach();
table.addLotsAndLotsOfRows();
parent.append(table);
40. The DOM is slow
Pull elements off the DOM while you toy with them
var table = $('#some-table');
var parent = table.parent();
new
table.detach();
in 1
.4
table.addLotsAndLotsOfRows();
parent.append(table);
41. Minimize DOM touches
Use classes, but if a style change user-selected:
jQuery('a.swedberg').css('color', '#BADA55');
jQuery('<style type="text/css"> a.swedberg { color: BADA55; } </style>')
.appendTo('head');
3000 Timings for X elements
2250 (1000 iterations)
1500 css()
style tag
750
0
1 5 10 20 50
43. Don’t treat jQuery as a Black Box
Use the source as your documentation
Add this to your bookmark bar, NOW!
http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js
http://bit.ly/jqsource
Determine which are convenience methods:
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
44. Don’t treat jQuery as a Black Box
Learn the lesser-known methods
map(), slice(), stop(), (de)queue(),
prevAll(), pushStack(), inArray() , etc
// index() in jQuery <= 1.3.2
$('#rdworth').parent().children().index( $('#rdworth')[0] )
// using prevAll() is 10% faster (also sexier)
$('#rdworth').prevAll().length
// in jQuery 1.4
$('#rdworth').index()
45. Don’t act on absent elements
jQuery is very kind and doesn’t throw errors at you
Don’t assume it’s just fine to do
$('#doesntexist').slideUp()
// this will execute genFx(), speed() and animate()
// before it hits an each()
jQuery UI widgets have a lot of overhead you’ll hit
46. Don’t act on absent elements
jQuery.fn.doOnce = function(func){
this.length && func.apply(this);
return this;
}
$('li.cartitems').doOnce(function(){
// make it ajax! o/
});
47. Don’t act on absent elements
$.fn.plugin = function(opts){
if(!this.length) return this;
var opts = $.extend(......
...
return this.each(...
54. Variable definition
// old 'n busted // new hotness
var test1 = 1; var test1 = 1,
var test2 = function() { test2 = function() {
// function code // function code
}; },
var test3 = test2(test1); test3 = test2(test1);
55. Munge the primitives
Define shortcuts at the top of your scope
Good for both compression and scope chain traversal
var TRUE = true,
FALSE = false,
NULL = null,
window = self,
undefined = undefined;
56. Munge the primitives
Define shortcuts at the top of your scope
Good for both compression and scope chain traversal
var TRUE = true,
FALSE = false,
NULL = null,
window = self,
undefined;
undefined = undefined;
58. var str=‘Let’s put this into
action’
// html.no-js html>
<!doctype ==> html.js
var elem = document.getElementsByTagName('html')[0];
elem.className = elem.className.replace('no-js','js');
<html class="no-js">
// quicker reference, safer replace
<head>
var elem = document.documentElement;
elem.className = elem.className.replace(/bno-jsb/,'js');
<script>
// one// change the html class to 'js'
line ftw!
// in the head, no FOUC
document.documentElement.className =
document.documentElement.className.replace(/bno-jsb/,
</script>
'js');
</body>
// shorter with a self-executing anonymous function
(function(B){B.className=B.className.replace(/bno-jsb/,
59. var str=‘Let’s put this into
action’
// html.no-js ==> html.js
var elem = document.getElementsByTagName('html')[0];
elem.className = elem.className.replace('no-js','js');
// quicker reference, safer replace
var elem = document.documentElement;
elem.className = elem.className.replace(/bno-jsb/,'js');
// one line ftw!
document.documentElement.className =
document.documentElement.className.replace(/bno-jsb/,
'js');
// shorter with a self-executing anonymous function
(function(B){B.className=B.className.replace(/bno-jsb/,
60. // html.no-js ==> html.js
var str=‘Let’s put this into
var elem = document.getElementsByTagName('html')[0];
elem.className = elem.className.replace('no-js','js');
action’
// quicker reference, safer replace
var elem = document.documentElement;
elem.className = elem.className.replace(/bno-jsb/,'js');
// one line ftw!
document.documentElement.className =
document.documentElement.className.replace(/bno-jsb/,
'js');
// shorter with a self-executing anonymous function
(function(B){B.className=B.className.replace(/bno-jsb/,
'js')})(document.documentElement);
// pass className, object string notation
(function(H,C){H[C]=H[C].replace(/bno-jsb/,'js')})
(document.documentElement,'className')
61. Conditionals
// old 'n busted
if ( type === 'foo' || type === 'bar' ) {}
// regex test
if ( /^(foo|bar)$/.test(type) ) {}
// obj literal lookup (smaller if <5 items)
if ( ({foo:1,bar:1})[type] ) {}
62. Logic and Ternary operands
// basic function detection
document.querySelectorAll && document.querySelectorAll('a:nth-child(2)')
// assignment is legal, but it evaluates to the right expression
callback && (isCallbackCalled = true) && callback(returnVal);
// call or cache the callback function
(isCallbackCalled || returnVal) ? fn(returnVal) : (callback = fn);
// inline function calls
isToday('Saturday') && Math.round(Math.random()) && $('#winnar').show()
// if JSON2.js or Native JSON is present, otherwise eval.
data = window.JSON && JSON.parse(data) || eval('('+data +')');
63. Write maintainable code
As a developer,
you should work first and foremost
for the user of your products.
The second most important person to work for is
the developer that takes over from you.
- Christian Heilmann
64. Comments
/*!
* Will not be removed by YUI Compressor
*/
// for quick toggling on and off:
/* */
aaaahYeah();
/* */
/* * /
ohHellNo();
/* */
66. Thanks, ya’ll.
Slides at http://paulirish.com/perf
@paul_irish
thx:
Alex Sexton, Ben Alman, Adam Sontag,
James Padolsey, temp01, #jquery on Freenode
67. todo
shadow effect to code samples
more context research and this: http://
groups.google.com/group/jquery-dev/msg/
b4b7935a4013dfe7 and http://ispeakwebstuff.co.uk/
web-design-development-tutorials/clever-jquery-
selectors/
68. `
// pngfix for IE6
// e.g. FL.pngfix('img.bigProdShot,a.thumb');
pngfix : function(sel){
// conditional comments for inclusion of that js.
if (typeof DD_belatedPNG == 'undefined'){ return;
} else {
// delay pngfix until window onload
$(window).load(function(){ $(sel).each(function()
{ DD_belatedPNG.fixPng(arguments[1]); }); });
}
} // end of FL.pngfix()
Editor's Notes
update the taskspeed shit.\ndelegation facts.\n
i hang in #jquery so a lot of examples are from real code discussed there.\n
\n
\n
\n
\n
like copypasting a line or three of code\n
\n
\n
\n
rebecca murphey will be discussing this technique a lot more\n
\n
\n
\n
\n
\n
the convenience of context will incur the cost of three extra if() statements in jQuery.fn.init()\n
\n
selectors. ugh.\n
did it because i wanted to study.\nthe old ones are probablyw ayyyyy easier to study as the new ones use some crazy techniques\n
did it because i wanted to study.\nthe old ones are probablyw ayyyyy easier to study as the new ones use some crazy techniques\n
\n
before sizzle it was LTR. sizzle changed it.\n
before sizzle it was LTR. sizzle changed it.\n
before sizzle it was LTR. sizzle changed it.\n
be brief on the left\nthe more you can filter down the righthandmost expression, the faster it will run.\n
id is grabbed. optimization\n
in my testing it didnt speed up basic selecting.\n
\n
css engine too.\n
\n
TDs and LI&#x2019;s etccc\n
\n
\n
\n
\n
document.body as an append target is WIN\n
\n
\n
padolsey&#x2019;s research on animate()\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
strings take up a lot of space, so allowing them to be munged helps a lot\ncompress it and look for repetition\n