RequireJS: Best method to run page specific modules?

wilsonpage picture wilsonpage · Nov 7, 2011 · Viewed 7.3k times · Source

Example:

mysite.com/page1 depends on scripts in module1.js

mysite.com/page2 depends on scripts in module2.js

mysite.com/page3 depends on scripts in module3.js

Does anyone have any best practices for only running the Javascript required for that specific page. Before I started using RequireJS I would use only one Javascript file and init only the modules I needed for that page. like this


In page <head>:

var page = "pageTitle";


In Main JS File:

var myModules = {};

myModules.pageTitle = (function(){

    return {
          init: function(){
             alert('this module has been initiated');
          }
    }
})();


myModules[page].init();


Not really sure sure how a technique like this would work with RequireJS. Would love some feedback and advice on how others are doing this.

Answer

bert bruynooghe picture bert bruynooghe · Nov 7, 2011

I assume you have one main.js file for all your pages?

Anyway, typically you would use the data-main attribute of the script tag as explained in the API documentation, which would mean you have one main js file per page. This way, you can get rid of the literal javascript code in you page, and take full advantage of the RequireJS optimization step.

Example:

Develop you main.js file as a RequireJS module:

define([<dependencies go here>], function(){

    return function(pageTitle){
        //do you page dependent logic here
    }
}

In your html, you'll have something like:

<html>
<head>
<script src="require.js"></script>
<script>
    require(["main.js"], function(init){
        init("pageTitle");
    });
</script>