Skip to content

Instantly share code, notes, and snippets.

@czarpino
Last active February 22, 2017 10:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save czarpino/3b06134ac6f43e4b16f5 to your computer and use it in GitHub Desktop.
Save czarpino/3b06134ac6f43e4b16f5 to your computer and use it in GitHub Desktop.
RequireJS - Separating config from logic

RequireJS - Separating config and main module

The idea is to identify, from the same script tag that loads RequireJS, the appropriate main logic module to be loaded. This is done by adding a data-id and a data-logic attribute to the RequireJS script tag.

The data-id attribute is used to identify the RequireJS script tag while the data-logic is used to specify the main logic module to load. Using data-id over id attribute is preferred simply because of technical correctness as scripts do not have an id attribute.

Say we have the following dir structure:

web/
    js/
        lib/
            require.js
            jquery.min.js
        config.js
        home.js
        login.js
    homepage.html
    loginpage.html

If the script home.js holds the logic for the homepage then the corresponding script tag would be:

// homepage.html
<script data-id="requirejs" data-logic="home" data-main="js/config" src="js/lib/require.js"></script>

Similarly, if login.js holds the logic for the loginpage then the corresponding script tag would be:

// loginpage.html
<script data-id="requirejs" data-logic="login" data-main="js/config" src="js/lib/require.js"></script>

Then in js/config, the main logic module is loaded using the value of data-logic attribute.

// config.js
require.config({
    baseUrl: 'js',
    paths: {
    
        // fallback to local in case CDN fails
        jquery: ['https://code.jquery.com/jquery-2.1.1.min', 'lib/jquery.min'],
        
    }
});
    
// Load app logic as specified in `data-logic` attribute
require([document.querySelector('script[data-id="requirejs"]').getAttribute("data-logic")]);

While this approach requires the use of non-standard attributes, it also lends to a terser and less cluttered way of separating the config from the main logic module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment