It is considered a best practice to push as many javascript script blocks or script files as possible to the bottom of your page (or as close to the bottom you can get). This helps prevent any script execution from blocking the rendering of any parts of your page. In fact, if you run your page through Google’s PageSpeed Insights tool, you’ll get dinged. They’ll recommend that you “Eliminate any render blocking javascript”. In many Sitecore sites, this is pretty easily accomplished by just that – putting most of your script includes at the bottom of your layouts.
But what happens if you have only one rendering that needs a certain javascript library? Or you have a rendering that needs some custom javascript?
We recently had a situation where a client needed the ability to control some custom javascript on a page-by-page basis. To satisfy this requirement, we created a pair of HtmlHelper Extensions.
Now that we have these HtmlHelper extensions, we can emulate MVC’s native RenderSection (not available in Sitecore – try it, you’ll see!) and essentially “inject” script blocks into a specific place (i.e. the bottom!) of your main layout.
In your rendering, you can include a script library:
@Html.Resource(@<script src="~/scripts/myscriptlibrary.js"></script>, "js")
…or a custom script block:
@Html.Resource( @<script type="text/javascript"> $(document).ready(function () { alert('Hello'); } </script> , "js")
If you had a script block field in a content item in Sitecore, you could even render that directly from your model:
@Html.Resource(Model.ScriptBlockContentField, "js")
Then, in your layout, you would include the RenderResources helper method to render any Resources defined:
@Html.RenderResources("js")
This is how we satisfied the requirement for our project. Derek Hunziker also provides an alternative approach that utilizes Sitecore’s HTML Cache.
Happy Sitecore trails, my friends!