What is head.js
From the same author as the fabulous JQuery Tools library – head.js is "the only script in your head". You include it in your HTML output, and write code for it to include and run other JS files. It also offers some extensions for CSS, for instance you can optimize for different screen resolutions or fix glitches in different browsers.
Why should you include your files via head.js?
Well, the browser will load in a blocking manner – that is, it will load the resources it encounters first, and then continue loading the other resources. If you have a bunch of JS files, they might take a while to load (think of the HTTP request overhead, and of network latency!), thus blocking images, CSS files and other content on your site.
Head.js is only one (small) JS file to include, which will take care of loading your JS files asynchronously and simultaneously in the background. Once they are ready, you can execute code using the head.ready() method.
The result is – your webpage display significantly faster!
Problem
Sometimes, the scripts you load via head.js will work, sometimes they won't – i.e. features of the site additionally coded by you will not show up constantly and predictably.
Solution
The problem may be a race condition. Head.js loads the scripts asynchronously, so sometimes the other code on your site gets executed before the JS files included via head.js are executed, and sometimes afterwards.
Example: you are passing some information to your script via a variable which differs from page to page.
Your code is something like this (actually I moved the call to head.js() to the head.min.js file itself, which may contribute to the problem!):
<script language = "JavaScript" src="includes/head.min.js"></script>
<script type="text/javascript">
head.js('includes/jquery.tools.min.js','includes/custom-script.js');
… lots of code inbetween …
var variable_to_pass = 'some value';
</script>
and in your custom-script.js you rely on variable_to_pass like this:
var i_rely = variable_to_pass;
Sometimes your variable_to_pass will get set up before head.js has loaded your custom-script, and sometimes not. In the first case, all will go well, in the latter case, your code will fail. In Google Chrome, for instance, silently, unless you activate the JavaScript console to see the error stated.
This is called a race condition. The solution to this condition is to rely on external variables only once the whole page has loaded and is scriptable, which you have to test for, extra.
For instance you could use JQuery's $(function() {]); method for this, setting up the dependent variable or using the passed variable inside the function.
Another possibility is to check if the variable is as of yet undefined, and to give it a default value.
if (typeof(variable_to_pass) === 'undefined') {
variable_to_pass = 'some default value';
}
(not writing var before the variable will make it global).