Showing posts with label RequireJS. Show all posts
Showing posts with label RequireJS. Show all posts

Monday, January 13, 2014

RequireJS and ASP.NET MVC

RequireJS is a javascript file and module loader.  It is used to load your javascript frameworks/plugins dynamically when needed and can optimize the time taken by your website to load your pages.

I'll demo a simple ASP.NET MVC 3.0 Application with RequireJS

Step 1: Download latest version of RequireJS from

Step 2: Create an ASP.NET MVC project and include the require.js file in your _Layout.cshtml page or Site.Master if you're using ASP.NET MVC 2.0.

<script src="@Url.Content("~/Scripts/require.js")" data-main="/scripts/main.js" type="text/javascript"></script>

data-main  attribute refers to main.js file which would act as a single point of interaction.  You can load all your javascript files dynamically through this js file.  This attribute would load the main.js file asynchronously after require.js file is loaded.

Step 3: Include jquery file in your scripts folder

Step 4: Add a div with the id="container" in a view

Step 5: Below is the code for Main.js file

require(['Scripts/jquery'], function () {
    $().ready(function () {
        $('#container').html("Hey! Require.js rocks!!");

The code above loads jquery file dynamically and initializes the document.ready event.  The code would simply insert a static html inside "container" div.

Note that "Scripts/jquery"  would be your path of jquery.js file excluding the ".js" extension.

For example, if you are refering to a file jquery-1.10.1.js located in scripts folder, you have to use require(['Scripts/jquery-1.10.1'],....)