Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequireJS: Best method to run page specific modules?

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.

like image 638
wilsonpage Avatar asked Nov 07 '11 10:11

wilsonpage


People also ask

Is RequireJS still relevant?

RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.

What is the difference between RequireJS CommonJS and AMD loaders?

The main difference between AMD and CommonJS lies in its support for asynchronous module loading. "The main difference between AMD and CommonJS lies in its support for asynchronous module loading."

Is RequireJS synchronous?

So, RequireJS doesn't support it. From your use case it seems that you don't need synchronous RequireJS, you need to return result asynchronously. AMD pattern allows to define dependencies and load them asynchronously, but module's factory function must return result synchronously.

What is Shim RequireJS?

shim: Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value. Here is an example. It requires RequireJS 2.1. 0+, and assumes backbone. js, underscore.


1 Answers

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>
like image 125
bert bruynooghe Avatar answered Sep 20 '22 23:09

bert bruynooghe