Simple Optimization to make your Website Faster

Since my first course in Javascript 5 years ago, I was taught like a good web developer that you should always put your javascript declarations in the header tag of your HTML page. The reasoning behind this is quite logical. If you’re attaching and element events to functionality (such as a buttons “onclick” event) you want that functionality defined before a user sees the button.

This tradition is starting to break though. More recently, we are wrapping all the javascript of our page in a large “onload” event (or in jQuery, the $(function() { .. }) to ensure the DOM loads before. We attach events to buttons after the page is loaded. The reasoning behind this is it allows the user to see the page starting to load more quicky, even if functionality isn’t available right away. So, if we’re waiting on the onload even anyways, then why isn’t loading external javascript files the last thing we do anyways?

All HTML Page Types

This is a simple change you can apply to your websites right now. Try it! Take all the javascript declarations and put them as the last thing that your page loads. If you have and <script> tags throughout your application that run onload, you won’t need to move anything because they will naturally run after the javascript libraries load (however, if you are using jQuery and have encapsulated code in the $(function() { … } declaration, this will of course need to be moved after your javascript imports).

Your page content should now load before functionality giving you a boost in speed and give the user a more responsive looking website.

Razor Pages

Razor has simplified this process even more with their _Layout pages. Using “RenderSection”, for each of your content pages you can pull all the pages javascript together and put it in a section called scripts.

index.cshtml

<!-- HTML Content here -->
@section scripts
{
<script type="text/javascript">
	// javascript here
</script>
}

Then, you simply modify your _Layout.cshtml page like so.

_Layout.cshtml

<!-- Header content -->
<body>
@RenderBody()
@Scripts.Render(“~bundles/jquery”)
@RenderSection(“scripts”, required: false)
</body>

Caution

If you’re implementing this on an existing site, you might have to do some thorough testing to make sure none of your scripts are running before the declarations. For simpler sites, or ones that have been well coded without heavy reliance on external libraries (jQuery, bootstrap, etc …) you should have no problem applying this paradigm to your pages.

For anyone coding new websites, code your pages loading external javascript upfront!

Leave a Reply