I normally wouldn't suggest to compress this specific JavaScript file. The reason is because it's really powerful technique what you are trying to achieve, and it's on the included files where you need to put the effort on the compression, as they will tend to be longer than such a script as you are describing.
I personally use the following snippet, which I consider short because I have seen that it's unobtrusive, not sure if it's shorter than the one you are suggesting.
//JP_js-css_request.js
<!-- Append js and css to the <head> of the document on demand based on the page -->
function loadjscssfile(filename, filetype){
switch (filetype)
{
case "js":
{
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}
break;
case "css":
{
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
break;
default: break;
}
if (typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref)
}
var filesadded="" //list of files already added
function checkloadjscssfile(filename, filetype){
if (filesadded.indexOf("["+filename+"]")==-1){
loadjscssfile(filename, filetype)
filesadded+="["+filename+"]" //add to list of files already added, in the form of "[filename1],[filename2],etc"
}
}
I place this script in the head as and when I want to call a CSS or JS to be re-used but I want to check if it's been included already at the head we call loadjscssfile( [path_to_file/filename.extension]
, js or css.
That for me takes care of it. Also keeping this file editable (as it kind of short) allows you to do modifications that can affect many files and centralizing the process. Or for example if you want to add import for CSS, etc. One thing to mention is that if you are including jQuery libraries or Prototype, or Scriptaculous etc, you need to be careful to call this file at the end </head>
. The reason is that if it appends the file after a library can affect the bindings of functions related by another library.
So in short if you have
jQuery
jQuery UI v-xxx
Mootools
Scriptaculous
Prototype
libraries, you need to not only avoid conflict between libraries but to ensure that all JS framework or heavy stuff are loaded firstly. That ensures that you can call files to append to the head just after the JavaScript file is included. So far, it has heavily helped me out because I use http://jscompress.com and after checking a JS works good on a project, I compress the file and call loadjscssfile()
as a function over that one. Although sometimes it takes some time to load depending on how big the resource is.
:P
– Šime Vidas Nov 24 '12 at 22:19