What is the most efficient way to dynamically load a script file before proceeding with the rest of the code execution?

In my Angular home.component.ts file, I have added the script loading code as shown below:

export class HomeComponent {
   constructor() {
       this.loadDynamicScript();
   } 

   public loadDynamicScript() {
      var script = document.createElement('script');
      script.src = "../node_modules/xxxxxx/i18n/xx.min.js";
      script.async = false;
      document.head.appendChild(script);
   }

The issue I am facing is that the file is being loaded after the components are created, rendering it useless. How can I ensure that the file is loaded immediately after being appended to the document?

Answer №1

If you want to connect calls together, returning a promise is one way to achieve that

export class HomeComponent {
    constructor() {
        this.loadDynmicallyScript()
        .then(() => {
          this.doSomethingWhenScriptIsLoaded();
        });
    } 
     public loadDynmicallyScript():Promise {
        var script = document.createElement('script');
        script.src = "../node_modules/xxxxxx/i18n/xx.min.js";
        script.async =false;
        document.head.appendChild(script);
        return Promise((resolve, reject) => {
          script.onload = resolve;
        });    
     }

Alternatively, you can simply provide a function to the onLoad event handler for when the script finishes loading

export class HomeComponent {
    constructor() {
        this.loadDynmicallyScript()
    } 
     public loadDynmicallyScript():Promise {
        var script = document.createElement('script');
        script.src = "../node_modules/xxxxxx/i18n/xx.min.js";
        script.async =false;
        document.head.appendChild(script);
        script.onload = () => this.doSomethingWhenScriptIsLoaded();
     }

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

What is the method for displaying script commands within package.json files?

With a multitude of repositories, each one unique in its setup, I find myself constantly referencing the package.json file to double-check the scripts. "scripts": { "start": "npm run dev" "build:dev": "N ...

What is the best way to destructure a blend of React props and my own custom props in my code?

I have a requirement to develop a custom React component that serves as a wrapper for the Route component in order to create secure routes. The challenge I am facing is how to access the element property, which is typically specified in the <Route> e ...

Can we programmatically switch to a different mat-tab that is currently active?

Looking to programmatically change the selected mat-tab in a TypeScript file. I came across a solution for md-tab, but I need it for mat-tab. I attempted the suggested solution without success. Here's what I tried: HTML <button class="btn btn- ...

Angular 2: The *ngFor directive is unable to locate a suitable differing framework

Below is the code for client.service.ts clients: Client[]; getClientList() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token&apo ...

Angularjs 2 Error: Unable to access the 'infos' property of an undefined object using the Http Client

I've been working on an AngularJS app for about a week now, developing a backoffice application for my service. My main challenge lies in using data retrieved from a remote server. I have 4 HTTP GET requests in my app - 2 of them fetching lists of us ...

Error in Angular 2: Component unable to locate imported module

I'm facing an issue where a module I want to use in my application cannot be found. The error message I receive is: GET http://product-admin.dev/node_modules/angular2-toaster/ 404 (Not Found) The module was installed via NPM and its Github reposito ...

What could be causing the issue with my React Native app's release version not opening on a physical Android device?

I encountered an issue while trying to install the Release version of my application. In order to test both the debug and release versions on my physical and virtual devices, I utilized the following commands: ./gradlew assembleDebug, ./gradlew assembleRel ...

The issue arises when trying to pass multiple parameters with the Angular 2 router and encountering

After creating a sample Plunker to pass multiple parameters to the next page, I encountered an issue where the crisis center routing failed to work properly upon clicking on items. See the demonstration on Plunker here: http://plnkr.co/edit/ngNSsKBzAuhaP0E ...

How can I implement a master-detail view in Angular 2?

Update: I finally figured it out. After moving all the html from index.html to app.component.ts, everything started working perfectly. The method described below is the correct one. I've been facing an issue where I have a ParentComponent that retrie ...

Unable to determine all parameters for MatProgressSpinner

I am trying to incorporate Angular Material's Progress spinner component into my project. However, I am facing an issue when importing the module. import {MatProgressSpinnerModule} from '@angular/material'; The error message displayed in t ...

What is the best way to set the first option in a mat-select to be

My approach to date selection involves using 3 mat-select components for day, month, and year. You can view a demo of this setup here. In an attempt to improve the code, I decided to set the initial options as null by modifying the following lines: allDat ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

Having trouble with the lodash find function in my Angular application

npm install lodash npm install @types/lodash ng serve import { find, upperCase } from 'lodash'; console.log(upperCase('test')); // 'TEST' console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is un ...

What is the best way to ensure that a class instance only receives the necessary properties?

In my code, I have a function that takes in an object called DataObject and uses certain properties from it to create instances of a class. To determine which data object items should be assigned to which class properties, I use mappings in the form of a ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

Navigating Mixins in Ember CLI Typescript

I'm curious about the best approach for handling mixins in a typed Ember application. While removing mixins from the application is ideal, many addons do not yet support TypeScript. So, how can we effectively utilize Ember Simple Auth's applicati ...

Storing dates using Angular 2 and JSON for efficient data management

I've encountered a challenging issue with my Angular 2 application. I'm attempting to organize my API (MongoDB) in such a way that each new "post" added by the admin can be retrieved by date (not time) on the front end. Here's an example of ...

When running the command "ionic capacitor run android", the task of compiling debugJavaWithJavac failed in the capacitor app

After successfully creating an Ionic 6.19.1 application, I incorporated the variables.gradle file and ran the "ionic capacitor run android" command without any issues. Here are the variable details: ext { minSdkVersion = 26 compileSdkVersion = 30 ...

Troubles with Katex/ngx-markdown Display in Angular 16

In my Angular 16 application, I utilize the ngx-markdown library alongside Katex and other dependencies. A challenging situation arises when the backend (an LLM) responds with markdown text that conflicts with Katex delimiters during rendering. I attempte ...

Creating an Angular Confirm feature using the craftpip library

Trying to utilize the angular-confirm library, but finding its documentation unclear. Implementing it as shown below: Library - In button click (login.component.ts), ButtonOnClickHandler() { angular.module('myApp', ['cp.ngConfirm']) ...