Saturday, April 10, 2010

Minimizing external javascript requests down to zero.

So, the less requests the better right?
Here is an idea for efficiency freaks to bring amount of requests to external javascript files down to none. Here is how.

1. In your external css file define element:
#javascript { font-family: "alert('hello world')"; }

2. Now in your html page define element with id="javascript"
3. On window load run this (jquery example):
   $(function() {
       var sJs = $('#javascript').css('font-family');
       // here you might need to trim the double quotes off the ends of the sJs
       eval(sJs);
   });

I have not checked as to the amount of javascript you can stuff into css attribute. It is probable that you could insert your entire minified js file into it. Please post a comment if you get any results, just curious.

Another difficulty with this approach is that you would need to find a way to escape double quotes in your javascript before inserting it into css.

Other than that, it is pretty decent approach: your css loads in the header of the file. No additional requests for js. Minimal javascript needed to be on the page to eval it.

Comments? Ideas?

No comments:

Post a Comment