The document provides lessons on jQuery and Drupal optimization techniques, including using ID selectors for faster lookups, caching selectors in variables to avoid repeated lookups, and manipulating the DOM by creating elements in memory before adding them to improve performance.
4. Lesson 1: Selectors
Always use #id selectors
they are indexed in the DOM
Never just use .class selector
document.getElementsByClassName; but IE
traverses the entire DOM
5. Lesson 1: Selectors
Always use #id selectors
they are indexed in the DOM
Never just use .class selector
document.getElementsByClassName; but IE
traverses the entire DOM
Use element.class selector
this narrows the traversing
6. Lesson 1: Selectors
Use nearest #parent_id as your context
$(‘div.find-me’,’#in_here’).bind(‘click....
7. Lesson 1: Selectors
Use nearest #parent_id as your context
$(‘div.find-me’,’#in_here’).bind(‘click....
Avoid complicated selectors
internally they produce redundant for in...
loops
8. Lesson 1: Case Study
Views
override view.tpl.php
<div id=”
<?php print($name .'-'. $display_id); ?>
“ >
9. Lesson 2: Caching
Never use the same selector twice,
cache object in variable
var myElem = $(‘#id’);
myElem.appendTo(‘body...
myElem.css({opacity.....
myElem.addClass(‘fade...
10. Lesson 2: Caching
Never use the same selector twice,
cache object in variable
var myElem = $(‘#id’);
myElem.appendTo(‘body...
myElem.css({opacity.....
myElem.addClass(‘fade...
Leverage chaining
myElem
.appendTo(‘body’)
.css({opacity:0})
.addClass(‘fade’);
11. Lesson 2: Caching
global scope cached objects (as needed)
window.$$ = {property:value}
function foo(){
alert($$.property);
}
12. Lesson 2: Caching
global scope cached objects (as needed)
window.$$ = {property:value}
function foo(){
alert($$.property);
}
...or use Drupal object
Drupal.yourGlobal = {
var1:‘value1’,
var2:‘value2’,
.....
}
13. Lesson 3:Dom Manipulation
Avoid manipulating the DOM directly
create objects in memoryu
var myElem = $(‘<div>’).addClass(‘stuff’);
17. Lesson 4:Deferring scripts
Load scripts before closing <body> tag
for scripts that don’t run on page load
drupal_add_js(‘path/to/script.js’, $defer=true)
*improves download speeds*
18. Lesson 4:Deferring scripts
Load scripts before closing <body> tag
for scripts that don’t run on page load
drupal_add_js(‘path/to/script.js’, $defer=true)
*improves download speeds*
Execute scripts on $(window.)load()
instead of $(document).ready()
for UI controls,AJAX/AHAH logic, most event
handlers
19. Lesson 4:Deferring scripts
Load scripts as needed in your theme
functions or templates
opposed to loading them via your theme’s .info
file
use drupal_add_js()
20. Lesson 4:Deferring scripts
Load scripts as needed in your theme
functions or templates
opposed to loading them via your theme’s .info
file
use drupal_add_js()
...or use $.getScript() to load scripts
$.getScript(‘path/to/script.js’,callback)
*using callback is vital!*
*Doesn’t work in IE? Issues with Safari 2?*