Including Inline Script Prior to Dependencies | Comments (2)
Posted in Code on 29th July 2008, 11:53 pm by Stuart
The 6th Rule in Yahoo’s Performance Rules recommends placing script before the closing body tag to prevent blocking holding up the rendering of the page’s content. This works well but there are times where script needs to be output higher up in the page than it’s dependencies. Usually these occasions are as a result of some kind of constraint imposed by a CMS for example.
In this example I’m using jQuery but feel free to substitute jQuery for the your favorite framework.
The requirement is that there’s a need to run some code that would ideally use jQuery somewhere in the middle of the page. I could avoid the dependency and re-write everything without jQuery and for simple scripts this can be a good way to go. But, if I want to use some of the more complex jQuery features, then I really don’t want to have to re-invent the wheel or resort to including jQuery in the head of the document.
To get around the issue I knocked-up a simple inline script wrapper which makes it possible to set-up as many arbitrary functions as required and then run them via jQuery as soon as it’s available.
The code
Here’s the code for the inline script. All that’s required is an array to which arbitrary functions are added. For convenience an “add” method makes it easy to add new functions to the array.
<script type="text/javascript">
var muffin = muffin || {};
muffin.inline = muffin.inline || [];
muffin.inline.add = function(f){
muffin.inline[muffin.inline.length] = f;
};
</script>
Using this is as follows:
<script>
muffin.inline.add(function(){
$('#green')[0].style.backgroundColor = 'green';
});
muffin.inline.add(function(){
$('#red')[0].style.backgroundColor = 'red';
});
</script>
Lastly is the code that executes the code added to the inline array:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
$(function(){
if (muffin && muffin.inline){
for (var i=0, j=muffin.inline.length; i<j; i++){
muffin.inline[i]();
}
}
});
</script>
You can see this all together in the following inline wrapper example.
In conclusion, resorting to this sort of thing shouldn’t be necessary most of the time but when faced with such a imposed limitation this is one way to resolve the dependency in a generic and reusable way.
A final caveat is that one would just have to take care that it’s not abused to load scripts anywhere in the page when it’s not necessary.

[...] Colville has found an issue where he needed to output some JavaScript in the middle of a page, before a library that depended on it was available: The 6th Rule in Yahoo’s Performance Rules [...]
[...] n Including Inline Script Prior to Dependencies by Stuart Colville [...]