Inline Script Wrapper and Dependencies
Date : 2008 07 30 Category : Tech & DevelopmentStuart 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 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.
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.
This lead him to the following example
PLAIN TEXT HTML: <script type="text/javascript"> var muffin = muffin || {}; muffin.inline = muffin.inline || []; muffin.inline.add = function(f){ muffin.inline[muffin.inline.length] = f; }; </script> <script type="text/javascript"> muffin.inline.add(function(){ $('#green')[0].style.backgroundColor = 'green'; }); muffin.inline.add(function(){ $('#red')[0].style.backgroundColor = 'red'; }); </script> <div id="red"><p>This should be Red</p></div> <div id="green"><p>This should be Green</p></div> <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>This seems a little niche. You my run into this as you have server side components outputting things, but ideally you can fix that in your architecture and ship the JavaScript in the correct location.