Dzulqarnain Nasir

JavaScript performance and ASP.NET

July 10, 2012 | 2 Minute Read

Today I read Stop paying your jQuery tax by Sam Saffron. This article explains why it’s important to include your JavaScript files at the bottom of the page. It’s a good read, if you’re concerned about JS performance on your sites.

However, working with ASP.NET, there are times when appending your JS files to the bottom of the page is not an option, especially so when you work with partial views in which your JS functions accepts parameters generated by the application. For example, you have a partial view that accepts some parameters from some other view which is then used in one of your JS functions. But you want to include the jQuery library at the bottom of the page to reduce your initial loading time. However, the function you’ve included in your partial view relies on jQuery being defined before the partial view. So now the script fails because $ or jQuery is undefined when the browser hits it.

There are two ways about this. One, you can use a JS file loader like RequireJS (which I’ve recently started using) and HeadJS, or two, if your site relies solely on jQuery to start up, you can use a method explained by Colin Gourlay in his blog post Safely Using .ready() Before Including jQuery.

What he did was simple. Queue up all the functions that rely on jQuery at page load, and execute each and every one of them once jQuery has been included. Much like what RequireJS does. The downside to RequireJS is that it requires you to rewrite your code, whereas this method would work with all your current code simply because it creates a fake jQuery function that actually pushes the function that you’re trying to run into a queue array, and executes them once jQuery has been loaded.

However, if you’re planning to work with multiple libraries, maybe even your custom ones, you might want to have a look at RequireJS. You can, of course, use Colin’s method for other libraries as well, simply by modifying the code to detect your handlers. Plus, this piece of code is a lot smaller than RequireJS, although RequireJS also comes with a couple of other cool features.

As for me, I think that if you’re starting a new project, or have the time to modify your existing projects, give RequireJS a go. It’s actually pretty easy to work with. Otherwise, Colin’s method may just be what you’re looking for.