Page performance - defer unwanted scripts executions
September 11th, 2009 Filed Under Javascript, browser, jQuery, optimization, page performance, snippet
In extension to my previous post regarding deferring images I would like to share my thoughts about deferring unwanted scripts executions.
The process hungry operations in DOM manipulation include insertion or deletion of elements and attaching events to them. And if all of such DOM manipulation occurs at the page load time it literally hangs other stuff piped in the download queue; And we blame the network latency to be the culprit.
So how do we solve this problem. It is simple to say, “Yeah! that’s right”. But what’s the right way of doing the right thing is not well known.
I have tried my way of solving this problem. In this regard I suggest two measures to be taken:
1) Use Event Bubbling
2) Defer unwanted event attachments
1) Use Event Bubbling: Event Bubbling is something that happens naturally on the DOM tree. In plain english every event on the page bubbles up to its parent until it reaches the document element. For example if we have an HTML document having body>div>a tag. Then when you click on the “a” element, the javascript engine looks for any onclick handler assigned to the “a” tag if it is assigned then it will trigger it. Then it traverses up to the parent element which is the div tag. Now if the div tag is having any onclick handler then that will also get triggered and so on.
What we generally do is we assign all the click events to the corresponding elements so that when they are clicked the handler executes and performs something. Attaching this kind of event handlers to several elements on the page penalizes on the page download performance.
So what we do is, instead of assigning so many click handlers we can assign only one click handler to the document, where the cue ultimately reaches.
Now how do we know on the document level which element was clicked?
For that you have an event object which carries the information about the element on which the event occured. Reading the event object we can determine what to do. So basically you write a list of if ..else in the document click function.
Code:
//CENTRALIZED CLICK EVENT HANDLER
$(document).bind("click",function(e){
if(!e.button){//ONLY WHEN LEFT CLICKED
var et = e.target;
var qet = $(et);
if(et.className=="closeBut"){
window.close();
}
if((et.tagName == "LI")&& qet.parents("del")[0]){
//code to handle click on LI which has a parent DEL
}
}
});
The above code is based on jquery way of assigning handlers. In the above code you can see that the event object has a property called target which points to the object where the event occured. Now using that object you can truthify the condition to perform some activity based on the properties of that object or the surrounding objects. For example here we are checking for the className in one if condition and className and parent both in the other condition.
2) Defer unwanted event attachments: This measure is another trick to unburden your load time script executions. What we do here is club all the hover and mouseover event attachments into one sub-routine and trigger it when the user moves his mouse for the first time.
Generally we see that a user’s pattern of opening links or a web page includes getting distracted to some other links or checking emails while the page opens. So a user open a web page and opens another web page or goes to check his emails or just waits for the page to load.
Here if the user doesn’t move his mouse, the heavy operation of assigning mouseover or hover events to list(s) or whatsoever on the page has an opportunity to get deferred to a later time when actually the user comes to the page and is ready to interact with the page.
Code:
//ON DOCUMENT MOUSEMOVE
$(document).bind("mousemove",function(e){
if(typeof initHovers=='undefined'){
if($$("#oc .menu")[0]){//MENU
mainmenu($$("#oc .menu"));
}
$$=$;//DISABLING THE CACHING AFTER PAGE LOAD
initHovers = 1;
}
});
The above code does exactly what I have declared above. Here it checks for an undefined variable existence called “initHovers”. If it does not exist only then we execute the sub-routine and define the variable with a global scope. As a result the sub-routine execute only once on the mousemove event on the document. And we save few seconds/milliseconds on the page load.
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
Make your page lighter – defer images to load
June 21st, 2009 Filed Under Javascript, Tips & Tricks, comparisons, jQuery, optimization, snippet, utilities
As web professionals we are generally concerned with the page load time, especially when we have a lot of images loading from third party servers which adds up to the page performance.
Portal developers are mostly worried and concerned with this problem.
I and my friend Shon Thomas have tried putting some thoughts and developed a jQuery plugin which will solve this problem.
The technique used here goes as follows:
We do not assign the “src” value to the images we want to load dynamically. Instead assign that URI in a different validator-friendly attribute. For example, you can use “class” or “longdesc”.
Upon scrolling the page, the plug-in detects the images in the viewport area of the browser window and swaps longdesc(or class) with src.
In both the attributes(class and longdesc) I don’t see any problem and they can be used as per your convenience and belief.There could be some argument regarding usage of both of these attributes; But as far as I think I have my reasonable words for both.
1) class: 99% of the time you don’t assign a class name to any image, instead you control them with their parent elements. Even then, if you are so specific, use longdesc.
2) longdesc: longdesc is a very rarely used attribute. I don’t often see people using this attribute on the content images. Even then, if you are specific then either use class attribute or don’t use this functionality for that particular image(as simple as that).
The image html that your server spits should be somewhat like this:
<img src="http://o.aolcdn.com/shopping.aol.com/img/notavailable.gif" longdesc="http://ai.pricegrabber.com/pi/7/19/48/71948063_160.jpg" alt="Dansko Reese Dress Pumps - Calfskin Leather - For Women" title="Dansko Reese Dress Pumps - Calfskin Leather - For Women"/>
Source Code: The source code below is the plug-in which can go in your jquery plugin file(s) or can get included as a standalone include.
/**
* jQuery plugin: Lazy Image Loader
* version: 3.0
* Author: Vivek Pohre,Shon Thomas
* Website: (http://www.vivekpohre.com)
* Example: call lzload() at or after document ready
*/
function lzload(){
var w=window,adv=30,vph,tmpLD,nowView,collImg,imgTop,scrTop,ci;
function getVPH(){
//DETERMINE WINDOW VIEWPORT HEIGHT ALWAYS TO AVOID RESIZING BROWSER ERROR
if(typeof (vph = w.innerHeight?w.innerHeight:$(w).innerHeight()) != "Number")
vph = document.documentElement.clientHeight;
};
//SAVE THE Y AXIS IN TOP ATTRIB
getVPH();//GET THE VIEWPORT HEIGHT
imgTop = 0;//INIT IMGTOP TO ZERO--TEMP VAR
collImg = $("#content img").filter(':[longdesc]');//COLLECT ALL IMAGES HAVING longdesc ATTR
collImg.each(function(){
imgTop = $(this).offset().top;
$(this).attr("top",imgTop);
});
$(w).bind("scroll",function(){loadImgs()}).bind("resize",function(){getVPH();loadImgs()});//ATTACH SCROLL & RESIZE EVENT TO WINDOW
$.loadImgs = loadImgs = function(imgSet){//MAKE loadImgs FUNCTION PUBLIC
ci=(imgSet)?imgSet.show():collImg;//DECIDE COLLECTION FROM PASSED OR ALL DOM IMAGES
scrTop = $(w).scrollTop();
//DETERMINE THE Y-AXIS IN THE VIEWABLE AREA
nowView = (scrTop+vph+adv);
ci.filter(':[longdesc]').filter(':visible').each(function(i){
if($(this).attr("top")<nowView){
tmpLD = $(this).attr("longdesc");
if(typeof tmpLD!='undefined')
$(this).attr("src",tmpLD)[0].removeAttribute("longdesc",0);
}
});
ci=collImg;
};
loadImgs();
$("#content img").error(function(){
$(this).attr("src","http://o.aolcdn.com/shopping.aol.com/img/notavailable.gif");
});
}
Post Linx
Permalink | Trackback |
|
Print This Article | 2 Comments
Reverse Engineer Packer javascript
June 11th, 2009 Filed Under Good to know, Javascript, Tips & Tricks, browser, debuggers, firefox, gyan
Have you ever seen a code something like this:
eval(function(p,a,c,k,e,r){e=funct.... etc....
And you suffer reading the encoded code. No suffers now; because I am going to tell you a trick that will convert your packer code in a readable script.
And it is really simple …. just replace the eval word with alert and refresh your page. You can now copy the code from the alert box.
If you face the problem of copying it from the alert box then open firefox browser with firebug pre-installed.
Open the console using F12 key and paste the code in the editable window.
Now replace the first word “eval” with “console.log” and hit run.
Probably you would need Javascript Tidy to make it properly readable.
Enjoy Madi!!
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
Firefox eats lot of memory?
April 2nd, 2009 Filed Under Good to know, Patch, Tips & Tricks, browser, firefox
Great!! that you came across the same road where I was chuckling for a while thinking and getting annoyed…
No doubt its a great browser; But the plugins eat a lots and tonnes of memory of your system and also by default it stores a lots of history for you…
So to lessload its history go to the Tools>Options>Privacy and reduce the history from 90(default) to 10 or less days.
But still, when you open multiple tabs you still find it hogging your system memory. To work with a different memory expensive application like Photoshop or Outlook or Eclipse.. you need a lot of memory…
So what to do?
No worries… open your firefox browser… type “about:config” (without quotes) in the address bar.
Hit enter. Now right click on the white space somewhere and choose New>Boolean…
An input box will appear..
Put “config.trim_on_minimize” (without quotes)…. Hit enter
Now choose “true” from the list and hit enter.Restart your browser… it will only hog the memory when you are using firefox… otherwise when you minimize it… the system memory hogged by firefox is released.
Check the status of your memory by using the Windows Task Manager. Enjoy the great browser and its plugins.
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
javascript object looping
February 2nd, 2009 Filed Under Good to know, Javascript, Tips & Tricks, gyan
In javascript generally all of us must have seen the following construct.
for(i=0; i<arrayObj.length; i++)
{
// then the code
}
But more than 50% of the time you loop through some javascript object or some javascript array.
So in order to write less and convenient code, you can also write the same for in the following fashion
for(i in arrayObj)
{
//then the code
}
It pretty much does the same job of looping. The only difference is that it takes the help of the object to be looped through for looping.
And that means you cannot use this stylish construct for an artificial looping, because the for(i=0; i< ….. construct is nothing but artificial looping.
Someone will ask then how do we get the loop index. It is pretty straight forward to get the index in case of simple array. The “i” will always return the current index.
Post Linx
Permalink | Trackback |
|
Print This Article | 2 Comments

