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.

Inspired by David Artz, I 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 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 longdesc="http://www.w3schools.com/banners/XmlSpy2009_728x90.gif" alt="How may we help you today?" />

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: Dynamic Image Loader(Dil)
 * version: 1.0
 * Copyright (c) 2009 Vivek Pohre(http://www.vivekpohre.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * example: $(document).dil("attributeName");  // ATTRIBUTE WHICH WILL CONTAIN THE URL TO BE SWAPPED WITH SRC ATTRIBUTE
 */

$.fn.dil = function(attr){
    $.getVPH = function()
    {
            $.vph =0;//VIEWPORT HEIGHT STORED IN $ OBJECT TO ACCESS IT GLOBALLY
            //DETERMINE WINDOW VIEWPORT HEIGHT ALWAYS TO AVOID RESIZING BROWSER ERROR
            if(typeof ($.vph = window.innerHeight?window.innerHeight:$(window).innerHeight()) != "Number")
                $.vph = document.documentElement.clientHeight;
    }
    $(window).scroll(function(){//ATTACH SCROLL EVENT TO WINDOW
        var scrTop = $(window).scrollTop();
        $.getVPH();
        //DETERMINE THE Y-AXIS IN THE VIEWABLE AREA
        var nowView = (scrTop+$.vph);
        //COLLECT IMAGES HAVING "longdesc" ATTRIBUTE SPECIFIED
        var collImg = $("img["+attr+"]")
        //LOOP THROUGH IMAGES AND SEE IF ANY OF THEM ARE IN THE VIEWABLE AREA RANGE
        collImg.each(function(){
            if($(this).offset().top<nowView){
                if($(this).attr(attr).length>0)
                    $(this).attr("src",$(this).attr(attr)).attr(attr,"");
            }
        });
    });
    //FIRE SCROLL EVENT ON READY SO THAT THE IMAGES IN THE INITIAL VIEWPORT GETS DISPLAYED
    $(document).ready(function(){
    $.getVPH();
    if($.vph<$(document).height())
    {
        window.scrollTo(0,1);window.scrollTo(0,0);
    }
    else
    {
        $("img["+attr+"]").each(function(){
            $(this).attr("src",$(this).attr(attr)).attr(attr,"");
        });
    }});
};

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

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. 

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.

Ajax Data - HTML vs. XML vs. JSON

December 19th, 2008   Filed Under Good to know, Javascript, Thinking Out Loud, Tips & Tricks, gyan, json  

Ever wondered why Ajax stands for ‘Asynchronous Javascript And Xml’? I was thinking about it and realized that the ‘x’ is never used or let us say of almost no use.

Classically when introduced by Microsoft, xmlhttprequest object might have been thought to  transport XML for the data transfers, as that was the most popular format which was known as the lightest in weight. But they forgot about the json.

Moreover, the scenario where we are standing today is really different than what had been thought earlier.

What was needed classically was to make a hidden request - get the response - inject in html - and show the result. But for this people started using the xmlhttp object as htmlhttp object. I mean rather than only transporting data, they are using HTML strings attached with the data(or the other way round).

I will show how can we make the request and response lighter and show results faster on the page so that the users don’t have to wait even on the dial up connections.

First let us compare the strings that are sent in a response in different formats.

HTML:

<div class=”resultArea”><h3>This is the result of  your query</h3><p><span>Request Num:</span>4564545<br/><span>Status:</span>Pending</p></div>
XML:

<resultArea>
    <heading>This is the result of your query</heading>
    <requestNum>4564545</requestNum>
    <status>Pending</status>
</resultArea>


JSON:

{heading:”This is the result of your query”, requestNum:”4564545″, status:”Pending”}

Clearly you can see which one uses less number of characters.
Not only that, you are only an eval() away from start using the object with the luxury of (.) dot notations. What else do you need?

Had we been using HTML,  we would have transported unnecessary HTML text along with the pure data to the browser. Just imagine the amount of repetitive HTML in case of a tabular data.

Using XML is also not so convinient because besides being bulky with its starting and ending tags, it is also needed to read via the DOM to traverse through the XML, which is time consuming, resource hungry and inconvinient code.