What is RequireJs: the browser module loader ?

About

RequireJs 1) is a browser module loader that implements the AMD specification . It may load also other modules (UMD, CommonJs)

Example

Basic: Loading a third party library to tell you your browser

In this example, we will load the bowser UMD library in order to get information about your browser.

  • Adding the require library in your HTML page
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
require(['https://cdnjs.cloudflare.com/ajax/libs/bowser/2.11.0/bundled.min.js'], function(bowser) {
   const browser = bowser.getParser(window.navigator.userAgent);
   console.log(`Your browser name is "${browser.getBrowserName()}"`);
});
  • Output:

Advanced: Loading with moduleId and SRI

The steps:

  • Add the require library in your HTML page
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  • Main: All the code below is the main. It is included now for convenience in the page but it could have been written in an external script and loaded via the data-main attribute added to the previous requirejs script tag with an async attribute
  • In a script tag, add the require configuration. It specifies:
    • in paths: two external module (script) and their corresponding module id:
      • domReady: a polyfill that ensures that the DOMContentLoaded has occurred
      • bowser: the third party library to gets information on your browser
    • in onNodeCreated: their respective SRI
require.config({
    paths: {
        "bowser": "https://cdnjs.cloudflare.com/ajax/libs/bowser/2.11.0/bundled.min",
        "domReady": "https://cdnjs.cloudflare.com/ajax/libs/require-domReady/2.0.1/domReady.min"
    },
    onNodeCreated: function(node, config, module, path) {
        // Here's  alist of differet integrities for different scripts
        // Append to this list for all scripts that you want SRI for
        let sri = {
            "bowser": "sha512-hsF/cpBvi/vjCP4Ps/MrPUFk6l4BqcGbzVUhqjJdX2SmAri1Oj8FBUGCvBiKHYd6gg3vLsV16CtIRNOvK5X4lQ==",
            "domReady": 'sha512-oeoXzE331hXr/6XbU7Vyi4cY7qg9DZuOSvSpl1gL66WyW3ghv+lV4all2A9Ht8TZ1mWIpqULz0R/hT7TdhhtlQ=='
        };

        if (sri[module]) {
            node.setAttribute('integrity', sri[module]);
            node.setAttribute('crossorigin', 'anonymous');
        }
    },
    waitSeconds: 5
});
  • The real code:
// Wait until the DOM is loaded (not needed but for demo purpose)
require(['domReady'], function() {
   // Load bowser and pass it along
    require(['bowser'], function(bowser) {
        const browser = bowser.getParser(window.navigator.userAgent);
        console.log(`Your browser name is "${browser.getBrowserName()}"`);
    });
});
  • Output:

Syntax

RequireJs implements the AMD api, therefore for the AMD require in RequireJs, the function is fired if the module:

  • don't wrap its code in a define function, when the module script is loaded.
  • wrap its code in the define function with dependencies when all dependencies of the module have been loaded

Module Support

AMD (UMD)

It implements a AMD environment.

  • You require a module, to get back the module export variable in a callback and to use it in your code
require("module", function(export) { export.function ... })
  • You may wrap your module with the define function to create and call dependencies

Because AMD is included in the UMD signature, all umd module are also supported

CommonJs

It also supports CommonsJs format 2)

define(function(require, exports, module) {
    //Put traditional CommonJS module content here
});

Esm

Esm module are not support (for now 2022/05/16). You can use a dynamic import.

Support

Dojo: has.add is not a function

The CDN version of Dojo is built assuming that you are using the Dojo loader in order to decrease code size. Part of the code removal is the alternative has.js implementation that is used if a loader doesn’t include one (like RequireJS). You can use a regular downloaded version of Dojo with RequireJS and it will work fine, but you can’t use the CDN version.

When using dojo, it's best to use the Dojo loader.

has.js.uncompressed.js:101 Uncaught TypeError: a.add is not a function
    at Object.<anonymous> (has.js.uncompressed.js:101:3)
    at Object.execCb (require.min.js:1:16727)
    ....





Discover More
Dojo (Dojo Toolkit)

dojo is a framework based around the AMD module and specification that provides: an module loader (adoption of bdLoad) based on the AMD specification (ie equivalent to RequireJs) and a wide range...
How to load a script dynamically with Javascript?

This page shows you how you can load a script dynamically with Javascript to load and use it when needed. In short, if you add: a script via an DOM element, it will be executed (via append or insertAdjacentElement)...
Javascript - Asynchronous Module Definition (AMD)

The AMD specifies a mechanism for defining modules such that: the module and its dependencies can be specified and loaded asynchronously. ie Both the module and dependencies can be asynchronously...
Javascript - Module Loader (Script Loader)

A loader searches and loads module and script into the javascript engine (environment). From the main script, they will: create a dependency graph from the require and import statement find them...



Share this page:
Follow us:
Task Runner