LazyLoad on JavaScript Load only once

What? And what’s the point?

On some web pages, the focus is displaying information fast, but also being aware that some actions that rely on a kinda heavy framework such as jQuery/Prototype/Dojo (Ajax+Animations+etc..) may still be done in page by a minority of users.

I believe the use cases of this technique are sparse, but would be around pages focusing Mobile Phones, where the processing and bandwidth are limited and pages that should prioritize very fast loadings.

To solve several browsers implementation for calling for JS after the page is fully loaded I used this library (LazyLoad 2.0) by a great programmer, a non-evil-doer. With this great lib is pretty easy to call a JS (or css for that matter) but is complicated to know when the Framework  you required is already loaded ( in the case that multiple acions may trigger the load)

For this case I developed a sort of proxy-function that should do the job in the following way:

        function load_and_run( callback, arg ){
		if( typeof($) == 'function' ){
			// This means jQuery is loaded
			callback( (typeof( arg ) != 'undefined' ? arg : true))
		}else{
			LazyLoad.js('/javascripts/jquery-1.4.2.js', function(arg){
				j=$;
			        //as here you can use LazyLoad to require some plugin
				callback( (typeof( arg ) != 'undefined' ? arg : true) );
			}, arg)

		}
	}

The secret sauce there is that I simply verify if the $ ( signature of jQuery, Prototype and others) is already defined, and for that to work I must proxy other actions by load_and_run, as can be seen here:

var spinner = new Image();	spinner.name = "madd-spinner";	spinner.src = "/images/ajax-loader.gif";
	
	function up_request( id, node ){
		load_and_run( up_request_callback )
		node.parentNode.appendChild( spinner )
	}
	function up_request_callback( id ){
		j.ajax({
					url: '/ajax/up',
					data:{definition_id:id},
					//etc...
					})

Remember to always give some feedback about the loading process for your user, in my case, I use a spinner gif preloaded.

Lesson learned from building www.gasa.jaeh.net, can be seen on any definition page

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s