I have made a construction to defer loading javascript to speed up page loading. To deploy websites i use the YIU compressor to minimize the scripts, also for speed. There will be two versions of the scripts, one is compressed and orginal one is not. For example: example-min.js and example.js. Some javascripts will be loaded only when a functionality comes in and sometimes it needs more scripts (plugin idea).
Anyway, i want to know (if other js files are needed) if the 'host' js file is compressed, so when it is compressed it loads the minified version of the js file. If not (when developing) it loads the orginial file.
For example:
function myObject()
{
var o = this;
o.isJsMinified = function()
{ s = o.isJsMinified.toString(),ss='s= ';
return (s.indexOf(ss+'o.is')<0);
};
o.require = function( s, delay, baSync, fCallback ) // add script to dom
{
var oo = document.createElement('script'),
oHead = document.getElementsByTagName('head')[0],
f = (typeof fCallback == 'function')?fCallback:function(){};
if( !oHead )
{ return false; }
oo.onload = function() {oo.id='loaded'; f(oo); };
oo.type = 'text/javascript';
oo.async = (typeof baSync == 'boolean')?baSync:false;
oo.src = s;
setTimeout( function() { oHead.appendChild(oo); }, (typeof delay != 'number')?delay:1 );
return true;
};
.....
.....
if( <new functionality found> )
{
if( o.isJsMinified() )
{ o.require('new-min.js',800); }
else { o.require('new.js',800); }
}
.....
.....
}
When you look at the jsIsMinified() function i use a trick to detect if the function itself (the source) is stripped from spaces (minified version). But, there is a problem with firefox, it does not return the original formatting so it cannot detect any difference.
For example: // compressed by YUI compressor:
o.isJsMinified=function(){s=o.isJsMinified.toString(),ss='s= ';return (s.indexOf(ss+'o.is')<0);};
Firefox will display:
function () {
s = o.isJsMinified.toString(), ss = "s= ";
return s.indexOf(ss + "o.is") < 0;
}
The function fails in firefox, it always 'says' it is not compressed. Does anybody know a work-around for this?