I'm following the h5bp proposed pattern of slapping all your script files on the bottom of the page, save for Modernizr.
Now, here's me working on something in ASP.NET MVC 3. I'm creating extensions to the HtmlHelper
to compartmentalize the markup of some reusable elements / controls on the form. Something like @Html.GiveMeATableDammit()
would generate markup for a table.
My dilemma comes in right about here. What if the markup generated requires some jQuery to be run against it? To illustrate, let's say that a jQuery plugin function needs to be called against that table:
@Html.GiveMeATableDammit("a-very-dirty-mouthed-table")
//
// will generate customized HTML
<table id="a-very-dirty-mouthed-table">
<!-- some more stuff -->
</table>
<script>
// along with customized javascript to match
jQuery(function ($) {
$('#a-very-dirty-mouthed-table').giveMeSuperPowers();
});
</script>
The problem is, at the point of markup generation, jQuery doesn't exist yet, since jQuery is at the bottom of the page.
Now, barring the idea of moving jQuery to <head>
, how can I hold off the execution of that one function until the very end of the page, where jQuery already exists?
Unless there's some ASP magic to do this, one approach I've seen is to declare an array in the <head>
of your page, and push()
your ready
handlers to them, then, at the bottom (after jQuery) has loaded, run them:
<head>
:
var handlers = [];
Wherever:
handlers.push(function ($) {
$('#a-very-dirty-mouthed-table').giveMeSuperPowers();
});
</body>
:
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script>
handlers.forEach(function (val) {
jQuery(document).ready(val);
});
</script>