Dynamically load scripts in angularJs

Having multiple libraries and dependencies in my angularjs application is posing a challenge as I want to load them all using just one script, given that three apps are utilizing these dependencies. Currently, I have this custom script:

var initDependencies = {

  _dependencies: [
    '/path/to/jquery.js', '/path/to/angular.js', 'path/to/bootstrap.js', ...];
  ],

  _currentFolder: '/' + window.location.pathname.split('/')[1],

/**
 * Constructor
 */
  init: function() {
    initDependencies.createDependencies();
  },

/**
 * Get the current folder
 */
  getCurrentFolder : function() {
    return initDependencies._currentFolder;
  },

/**
 * Get the array of dependencies
 */
  getDependencies: function() {
    return initDependencies._dependencies; 
  },

/**
 * Create a new <script> tag with its src
 * @param {*} src 
 */
  createNewDependencie : function(src) {
    var myScript = document.createElement("script");
    myScript.type = "text/javascript";
    myScript.src = src;
    console.log('myScript :', myScript);
    document.body.appendChild(myScript);
  },

/**
 * Create all dependencies
 */
  createDependencies: function() {
    for (var dependencie in initDependencies.getDependencies()) {
        var src = this.getCurrentFolder() + initDependencies.getDependencies()[dependencie];
        initDependencies.createNewDependencie(src);
    }
  }
}

document.addEventListener("DOMContentLoaded",initDependencies.init);

However, I am encountering errors with other dependencies listed in my dependencies array, resulting in several instances of:

Uncaught TypeError: Cannot read property 'module' of undefined
(indicating that the angular variable may not be defined).

Is there a way to efficiently load my dependencies and libraries dynamically?

Answer №1

Many developers opt to pre-build their projects for specific targets using task runners like Grunt or Gulp. These tools, which run on NodeJS and are easy to set up, can streamline the building process based on different environments or deployment targets, resulting in smaller and more efficient JS code files.

In addition, NodeJS offers built-in functions that can handle many tasks without the need for additional builders. By utilizing NodeJS, developers gain access to features that browsers lack, such as filesystem permissions, making it easier to prebuild everything needed for a project.

This approach not only simplifies the process but also improves speed by allowing for actions like uglifying and minifying scripts upfront, rather than loading large libraries while the user waits for results.

The use of NPM with NodeJS further enhances productivity by managing dependency versions effectively. This centralized system helps in maintaining dependencies over time, ensuring smoother project management.

By setting up a well-configured dependency file and running a builder for specific environments, developers can effortlessly create new applications within seconds, utilizing existing organizational structures and making versioning more practical and efficient.

If you haven't already explored this method, I highly recommend considering it for any serious project. Embracing this approach can offer substantial benefits compared to alternative strategies.

While I intended to provide these insights as a comment, the length of the explanation necessitated a separate response. Merely stating "use a builder" would have oversimplified the value of this comprehensive approach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

Setting the offset for panResponder with hooks: A step-by-step guide

While exploring a code example showcasing the use of panResponder for drag and drop actions in react native, I encountered an issue with item positioning. You can experiment with the code on this snack: The problem arises when dropping the item in the des ...

Two commands, a set of matching controllers, and an identical templateUrl

As a beginner in AngularJS, I am facing a challenge where I need to use one template for two directives. The issue is that the behavior of the first directive overrides the second one, even though I have specified different controllers for each. This seems ...

Having issues with default sorting and searching not functioning in Datatables with Angularjs

Utilizing a directive to facilitate database building once ng-repeat has completed: app.directive('repeatDone', function() { return function(scope, element, attrs) { if (scope.$last) { scope.$eval(attrs.repeatDone); ...

The integration of VueJS with the Canva Button JS API amplifies the

I have been exploring Canva's Button JS API which can be found at My goal is to implement a modular approach in utilizing their API, only loading the CanvaJS when necessary. My implementation involves triggering the load function when a button is cli ...

The invocation of Firebase ref.once() seems to have inexplicably gone unnoticed

I've been working on an alarm app with Firebase integration. The goal is to add 3 sample tasks to the list when a user first uses the app, and save them to Firebase. However, I'm facing an issue where these sample tasks keep getting added every t ...

What could be causing the data in the data table to remain undeleted unless the page is manually refreshed

I am facing an issue with the delete button functionality. When I press the button, it successfully deletes the row but requires a page refresh to make the deleted row disappear. How can I resolve this problem and ensure that the row is deleted without the ...

Experiencing a problem with a loop in iMacros/JS?

I have an iMacros/JS script for Facebook that logs into a FB account from a CSV file, then it has a second loop j which sends 20 friend requests from each account. The issue arises when switching accounts and encountering a popup message requiring phone n ...

What could be causing the malfunction of my Superfish menu in Firefox?

I am currently experimenting with the Superfish jQuery plugin to improve a drop-down menu on my website. Unfortunately, in Firefox browser (v. 21.0), the drop-down menu does not open when hovering over it as expected. However, it works fine in Chrome and O ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

Can you switch out the double quotation marks for single quotation marks?

I've been struggling to replace every double quote in a string with a single quote. Here's what I have tried: const str = '1998: merger by absorption of Scac-Delmas-Vieljeux by Bolloré Technologies to become \"Bolloré.'; console ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

Tips for layering one div on top of another div

I'm looking for guidance on how to position my button divs over my Trapezoids in an overlay fashion. Currently, I have set up an array to store the colors and utilizing the map function to match each button with its corresponding color type. When a ...

Exploring Javascript/JQuery parameters based on data types

I'm a bit confused about whether the title accurately reflects my question. I need help understanding how jQuery deals with functions that are called with different argument combinations, such as ("Some String", true, function(){}) and ("Some String", ...

Chrome on IOS: Experiencing screen freezing while scrolling

1) I'm working with Material UI in React JS. I have added a simple scrollable code, but when I reach the bottom of the screen/scroll, it freezes. 2) I also tried it with a simple HTML page and it worked correctly. <div style={{ ...

Setting up a CentOs Linux environment to host and run a node.js server

Just installed node.js on my new VPS server. I have written a basic script called "server.js" and it is currently running on port 8080. The location of the script is in the "var/www/html/" directory. However, whenever I try to access my domain, it only dis ...

sending data from a callback to an express router

As I embark on learning node.js, I've encountered a challenging issue. In my passportAuth.js file, I create a user and have a callback to ensure the user is created successfully. The code snippet looks something like this: req.tmpPassport = {}; var ...

Saving information to a hidden div using jStorage

Currently, I am utilizing jStorage for storing data in local storage. When I store the data using console.log() and later retrieve it using $.jStorage.get(), I found that the values are not being assigned to the hidden div. Can someone provide guidance o ...

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...