What is the method for loading dynamic scripts within Angular?

Angular Version: 7.1.4

In an attempt to resolve the issue of script loading errors, specifically 'Uncaught TypeError: Can not read property Responsive' of undefined', I explored a potential solution which involved creating a service for dynamic script loading. Following a tutorial, I diligently implemented the necessary steps; however, the functionality did not perform as expected.

import { Injectable } from '@angular/core';

interface Scripts {
name: string;
src: string;
}

export const ScriptStore: Scripts[] = [
{name: 'jquery', src: 'https://code.jquery.com/jquery-3.3.1.min.js'},
{name: 'tables', src: '../../../assets/dashboard/js/tables.js'},
{name: 'widgets', src: '../../../assets/dashboard/js/widgets.js'},
{name: 'charts', src: '../../../assets/dashboard/js/charts.js'},
{name: 'theme.min', src: '../../../assets/dashboard/dist/js/theme.min.js'}
];

declare var document: any;

@Injectable()
export class DynamicScriptLoaderService {

private scripts: any = {};

constructor() {
ScriptStore.forEach((script: any) => {
this.scripts[script.name] = {
loaded: false,
src: script.src
};
});
}

load(...scripts: string[]) {
const promises: any[] = [];
scripts.forEach((script) => promises.push(this.loadScript(script)));
return Promise.all(promises);
}

loadScript(name: string) {
return new Promise((resolve, reject) => {
if (!this.scripts[name].loaded) {
//load script
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = this.scripts[name].src;
if (script.readyState) { //IE
script.onreadystatechange = () => {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
this.scripts[name].loaded = true;
resolve({script: name, loaded: true, status: 'Loaded'});
}
};
} else { //Others
script.onload = () => {
this.scripts[name].loaded = true;
resolve({script: name, loaded: true, status: 'Loaded'});
};
}
script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});
document.getElementsByTagName('head')[0].appendChild(script);
} else {
resolve({script: name, loaded: true, status: 'Already Loaded'});
}
});
}
}

Subsequently, I attempted to invoke this service upon component initialization in order to load the scripts

ngOnInit() {
this.loadScripts();
}

private loadScripts() {
// Multiple scripts can be loaded by passing the key as argument into the load method of the service
this.dynamicScriptLoader.load(
'jquery',
'tables',
'widgets',
'charts',
'theme.min'
)
.then(data => {
console.log('scripts loaded')
}).catch(error => console.log(error));
}

Despite my efforts, I encountered several errors when utilizing this service. Along with the persistence of the initial error, additional problems such as 'Failed to load resource: the server responded with a status of 404 (Not Found)' and 'Uncaught ReferenceError: c3 is not defined' from the 'charts' file arose. It seems that my implementation may contain incorrect calls within the service, despite referencing tutorials that appeared reliable.

Answer №1

After some careful re-coding of my HTML, I realized that I may have mistakenly included a script twice.

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 with react router v6: Component fails to render even though route has been changed

The router seems to be experiencing an issue where it does not render a component. Specifically, on the home page, the Private Route is only rendered once. Clicking on a NavLink changes the URL to "/agreements", but the component itself is not being render ...

Executing a Mongodb server on an android device with the help of Ionic 2

Recently, I've been working on running MongoDB on Android with Ionic 2. My app runs smoothly in my PC browser and fetches data from the MongoDB located in the project folder. However, when trying to run it on an actual device or emulator, I encountere ...

Performing a task once elements are added to an array

I created a function that calls an API to retrieve information for each product and then stores it in an array. After looping through all the products, I want to perform an action with the array. Here is my code: newProducts: any = [] loadOfferRelated(o ...

Navigate to a new page on button click using Row with Tanstack / React-Table and Typescript (2339)

Encountering a linting error when attempting to navigate to a new route by clicking on a table row. The functionality is working but how can I resolve this issue? It's showing an error message stating "The property "id" for type TData does not exist." ...

Utilize SystemJS to import chart.js within the index.html file

I am just starting to learn about angularjs (specifically angular js2). I am having some confusion with SystemJS importing and configurations. Currently, my angularjs2 application is working fine. I am developing it using Visual Studio. I have set up my ...

Tips for utilizing the @Input directive within the <router-outlet></router-outlet> component

I am new to Angular 4 and recently discovered that in Angular, data can be passed from a parent component to a child component using @Input like this: <child [dataToPass]="test"></child> My question is, how can I achieve the same functionalit ...

Adding a constant to a Vue component

Currently working on developing an application using Vue and TypeScript. I'm focused on refactoring some aspects, particularly moving hard-coded strings from a template to a separate constant. What has been implemented is as follows: export const va ...

The ngx-datatable encountered a resolution issue with its dependency tree and was unable to resolve it

I've been trying to incorporate ngx-datatables into an Angular 12 project by running the command npm install @swimlane/ngx-datatable. However, after installation, I encountered the following Errors: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to r ...

NgModel fails to properly bind value with dynamically generated checkbox inputs

When I click on the "edit" button in a row, a dynamically created form wrapped in a table appears. This form contains conditionals that display inputs when the row is being edited. The type and binding of these inputs are dynamic. Here is an example: < ...

Angular2's $compile directive functions similarly to AngularJS 1's $compile directive

I am currently in the process of migrating my project from Angular 1 to Angular 2 and I am in need of a compile directive. However, I am struggling to rewrite it to achieve the same functionality as before. app.directive("compile", compile); compile.$inje ...

Managing the "SafeValue must use [property]=binding:" error in Angular when using the (click) event

I am working on creating a Facebook share button, Component, ngOnInit() { this.WebURL = this.domSanitizer.bypassSecurityTrustResourceUrl(this.data.url); this.facebookURL = this.domSanitizer.bypassSecurityTrustResourceUrl("https://www.fa ...

DuplicateModelError: Unable to duplicate model after it has been compiled, React.js, MongoDB, TypeScript

In the early stages of developing an application using Next.js, Mongoose, and Typescript, I encountered a persistent issue. Whenever I attempt to send a request through Postman after clicking save, it fails, displaying the error message: OverwriteModelErr ...

The constant value being brought in from an internal npm package cannot be determined

I have developed an internal npm package containing shared types and constants. My project is built using TypeScript with "target": "ESNext" and "module": "NodeNext". Within one of my files, I define: export type Su ...

Encountering a 405 HTTP error in Angular8 app when refreshing the page

Currently, I am working on a project using Angular8 and .NET Core 3.0 in Visual Studio. Everything is running smoothly except for one issue that arises when I press F5 on a page with a form. The error message that pops up reads: Failed to load resource: ...

Customizing Bootstrap Styles in Angular: How to Override Specific Classes

Looking to customize an HTML element <div [style.color]="themeService.backgroundColor" class="col-md-10 col-md-offset-1 col-sm-10 col-sm-offset-1 col-lg-10 col-lg-offset-1"> <ul class="pagination" id="pag-bar"> <l ...

Contrasting the Appmodule and Pages module within Angular: A Comparison

After cloning this project, I noticed that it contains two types of modules: one inside the page and the other in the root directory. Directory Tree: https://i.sstatic.net/tjq0I.png App.module.ts import { BrowserModule } from '@angular/platform-bro ...

Developing an exportable value service type in TypeScript for AngularJS

I have been working on creating a valuable service using typescript that involves a basic switch case statement based on values from the collection provided below [{ book_id: 1, year_published: 2000 }, { book_id: 2, year_publish ...

Master the art of properly switching on reducer-style payloads in Typescript

Currently, I am dealing with two types of data: GenArtWorkerMsg and VehicleWorkerMsg. Despite having a unique type property on the payload, my Searcher is unable to differentiate between these data-sets when passed in. How can I make it understand and dis ...

Center the text vertically within a card using Vuetify styling

I am seeking a way to vertically align text within a card using Vuetify or traditional CSS in a Vue project. Here is my code: <template> <div> <v-container class="my-5"> <v-row justify="space-between"> <v- ...

The pagination button in angular bootstrap UI caused the button to shift when clicked

I am currently using angular bootstrap's UI pagination to display results with next and previous buttons. The result sets are displaying correctly, however, I am encountering an issue when clicking on the pagination buttons. Specifically, the buttons ...