-
Notifications
You must be signed in to change notification settings - Fork 5
Javascript
Moth handles all external javascript files. It can:
- Combine multiple files into one single request
- Minify files on the fly (via YUICompressor)
- Render all script tags at the bottom of the page
- Automatically expire client-side cached scripts on an update
You can register any script via:
<% Html.RegisterScript("~/scripts/jquery-1.5.1.js"); %>
You can do this from any type of view: master pages, views and partials.
To render all the script tags, put the following at the bottom of your master page, right before the </body>
tag. You want to do this because loading scripts blocks execution:
<%=Html.RenderScripts() %>
Because you are loading all javascript at the bottom of the page, you can't write javascript code in your views that is dependent on 3rd party libraries. For a solution, see Inline script.
By default, all scripts are grouped into one single request. This might not be the most efficient way, for example when you have site-specific scripts like jQuery; and page-specific scripts. In this case you'll want to group your global section of scripts into one request, as it allows for client-side caching, and group the page-specific scripts into another one. For this purpose Moth supports a second parameter for the RegisterScript
function.
<%
Html.RegisterScript("~/scripts/jquery.js", "global");
Html.RegisterScript("~/scripts/global.js", "global");
Html.RegisterScript("~/page-specific.js");
%>
All scripts are grouped based on the second parameter, so in this case we'll have 2 requests.
Moth sends the javascript requests automatically with long expire headers, so users won't have to load your resources every time. This allows for a faster loading of your pages on a recurring visit. When you update a javascript file, you will want to push the new version to your clients. Therefore Moth will automatically put a version number at the end of your requests, based on the hash of the content of all scripts. You won't have to do anything, Moth will handle this automatically.