How does RequireJS work with multiple pages and partial views?

asp.net-mvc, requirejs

Solution

Update - I've added an example of using RequireJS with modular HTML components. Build tool example included - https://github.com/simonsmith/modular-html-requirejs

I have also written a blog article about this - http://simonsmith.io/modular-html-components-with-requirejs/

The approach of just using `main.js` for everything is probably more suited to a single page application.

The way I've handled this situation is to only include common site-wide JS in the `main.js` file:

On every page:

<script src="require.js" data-main="main"></script>

main.js

require.config({
// config options
});

require(['jquery', 'common/ajaxLoader', 'common/someOtherModule'], function($, ajax, otherModule) {
    // Modules that do stuff on every page are instantiated here 
});

page1.html

<script>
    require(['scripts/page1']);
</script>

page1.js

require(['jquery', 'page1Module'], function($, module){
    // page1 specific stuff here
});

The above example is just one of a couple of ways to handle it. Note the difference between loading a plain JavaScript file and a module.

A rule of thumb I follow is to keep all reusable modules (or Classes if it makes it easier to conceptualise) inside a `define` with their own dependencies etc and then use `require` to grab those modules, use their methods or interact with them in some way.

Using this pattern will almost certainly require use of the domReady module that is a separate plugin for RequireJS. Use this instead of a ready function in jQuery for example, as it allows modules to begin downloading before the DOM is ready which reduces the wait for your code to execute.

Edit You may wish to see another example of multi-page application in the RequireJS repo

Problem

I'm looking into RequireJS but I'm uncertain about some things. I understand how I can load all my dependencies with `main.js`. But do I need to add any logic to work with those dependencies in `main.js`? To me, `main.js` seems like a document.ready state and you enter logic there when the document has loaded, right? And for other pages and partial views, do I need to create multiple `main.js` or can I just reference loaded functions in dependencies from the views in a `<script>` for example?

Original source