How to Add External JS via RequireJS in Magento

Adding external JavaScript libraries to a Magento application using RequireJS ensures that the library is properly loaded, optimized, and integrated into the application’s dependency management system. In this tutorial, we’ll walk through how to load an external JavaScript file hosted on a URL using RequireJS.

We’ll use a sample code snippet to demonstrate how to:

  • Configure RequireJS to load the external script.
  • Set up Subresource Integrity (SRI) for security.
  • Load the configured script in your project.

Step 1: Configure RequireJS

Create a configuration file to include the external JavaScript library. Here’s an example:

				
					require.config({
  paths: {
    'restrictinspect': 'https://hikmadh.com/restrictinspect'
  },
  onNodeCreated: function (node, config, module, path) {
    // Define Subresource Integrity (SRI) hash for security
    var sri = {
      restrictinspect: 'sha384-4ONa6XQxU+lW56a27oGUfsA43UV2LTT1kv9ibpfUN6QsowbrPEu9gJkXB3SJif1n'
    };

    // Apply SRI attributes if available
    if (sri[module]) {
      node.setAttribute('integrity', sri[module]);
      node.setAttribute('crossorigin', 'anonymous');
    }
  },
  deps: ['./app'] // Specify the main entry point
});

				
			

  • paths: Maps the library alias (restrictinspect) to the external URL.
  • onNodeCreated: Adds SRI attributes for secure loading. This ensures the script’s integrity.
  • deps: Specifies dependencies, like the main script (app.js), that should load after RequireJS is initialized.

Step 2: Integrate RequireJS in Your HTML File

Next, include the RequireJS library and the configuration file in your HTML. Add the following code to your HTML:

				
					<!DOCTYPE html>
<html>
<head>
  <script data-main="main.js" 
          src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.js"
          integrity="sha384-Rh64MlzyKveY4KwE+9IxuAKT76LZQnQ7AeHeOTgQ1BnwTrcpk2NFJU9rpAG/u7ae" 
          crossorigin="anonymous"></script>
</head>
<body>
  <p>Test</p>
</body>
</html>

				
			
  • data-main: Points to the main RequireJS configuration file (main.js).
  • src: Loads RequireJS from a trusted CDN.
  • integrity and crossorigin: These attributes ensure secure loading of the RequireJS script.

Step 3: Define and Use the External Library

Once the external JavaScript library is configured in RequireJS, you can use it in your modules. Here’s an example module that logs a message:

				
					define(['restrictinspect'], function ($) {
  console.log('This is How to add external JS via RequireJS in Magento', $);
});

				
			

define: Declares a module with a dependency on the restrictinspect script.
The callback function receives the loaded library ($) as a parameter, allowing you to use it in your code.

Final Thoughts

Using RequireJS to load external JavaScript in Magento (or any application) has several benefits:

  • Modularity: Allows structured and maintainable code.
  • Security: Integrating SRI protects against script tampering.
  • Performance: RequireJS optimizes script loading and dependency management.
By following this guide, you can seamlessly integrate any external JavaScript library into your project. Happy coding!