Ways to incorporate External JS and CSS files into Angular 5 (loading files with a delay)

I have encountered some challenges while attempting to import external JS and CSS files into my Angular 5 application.

Below is the code snippet that I have tried so far:

Component.ts :

  ngOnInit() {
    this.loadScript();        // also attempted with constructor
  }

  loadScript () {
    const head = document.getElementsByTagName('head')[0];
    const link = document.createElement('link');
    const s = this.document.createElement('script');

    s.type = 'text/javascript';
    s.src = 'https://**/assets/js/patterns/name.min.js';

    link.id = 'pattern';
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = 'https://**/assets/js/patterns/name.min.css';
    link.media = 'all';

    head.appendChild(link);
    const __this = this;
    s.onload = function () { __this.afterScriptAdded(); };
    this.elementRef.nativeElement.appendChild(s);
 }

I also tried loading from an scss file by adding this line:

 @import url("https://**/assets/js/patterns/name.min.css");

While I can see the files in the network tab, there seems to be a delay in their loading. This results in my functions rendering without these dependencies, only for them to load later when not needed anymore.

The solution currently works only upon reloading, switching between components freezes the first time and only displays properly after a page refresh, along with the dynamic scripts connected.

I've come across several questions on this matter but haven't found a working solution yet:

  1. Dynamically load external javascript file from Angular component
  2. How to load external scripts dynamically in Angular?

If anyone has faced a similar situation before, any assistance would be greatly appreciated :)

Answer №1

At first, I attempted to find a solution without using the setTimeout function.

However, it appears that the only way to make this work is by delaying the loading of files, allowing the component to fully render before attaching our JavaScript (+ CSS) file to the native element.

...

ngOnInit() {
   setTimeout(() => {
        this.loadScript();
   }, 100);
}

...

While this method is effective, it still relies on a static timeout value. If you have a better solution, please share it with me.

Happy Coding. :)

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

Animating Angular on the table row element

I am currently displaying a table with a list of items that are updated via polling using an http get request to the server. The response is rendered only if there have been changes in the data. My goal is to add animations to the rows of the table and tr ...

The TypeScript compiler is unable to locate the identifier 'Symbol' during compilation

Upon attempting to compile a ts file, I encountered the following error: node_modules/@types/node/util.d.ts(121,88): error TS2304: Cannot find name 'Symbol'. After some research, I found that this issue could be related to incorrect target or l ...

The module 'DynamicTestModule' experienced an import of an unexpected value under the name 'SohoComponentsModule'

I have been working on an angular 2 application using our UI team's library. The progress has been smooth, thanks to the easy integration of their components through import statements in my app.module.ts: import { BrowserModule } from '@angular/ ...

How to Retrieve a Variable from the Parent Component in a Child Component using Angular (1.5) JS

I am currently working on abstracting the concept of a ticket list building into an angular application using 2 components. 1st component --> ("Smart Component") utilizes $http to fetch data and populate an array called populatedList within the parent ...

Having trouble mocking useAppSelector in Jest, RTL, Redux Toolkit, and React testing

I have react redux toolkit installed and have replaced vitest with jest for testing purposes. My goal is to test whether the modal window is rendered in the App component when the isOpen flag is true. I only mock the part of the store that is necessary, n ...

Are there any risks associated with using nested setTimeout functions with the same name?

While reviewing the source code of typed.js, I noticed that the main function in this plugin utilizes a design pattern with multiple setTimeout functions nested inside one another. Here is a snippet of the code: self.timeout = setTimeout(function() { / ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

custom form control component combined with an issue

Trying to develop a custom MatFormFieldControl with ControlValueAccessor implementation. Starting off with a familiar scenario: password form. The objective is to design a form field that takes a single string input, but contains its own internal form fo ...

"Exploring the differences between request.body, request.params, and request.query

I am working with a client-side JS file that includes: agent = require('superagent'); request = agent.get(url); Afterwards, the code looks something like this: request.get(url) //or request.post(url) request.end( function( err, results ) { ...

Utilize knex.js and TypeScript to create queries with specific conditions

I am trying to create a dynamic query that will include a where clause based on whether the variables name and/or city are passed. While I couldn't find a specific method for this in the documentation, I attempted to add the where clauses directly to ...

Is Nextjs prone to creating identical pages during the build process?

I have a question that I couldn't find the answer to anywhere, so I hope someone here can help me. I have a blog and I want to use SSG for the homepage and ISR for individual posts. If I set up my homepage using SSG to display 10 posts like this: ind ...

My HTML table is not printing at full width

Seeking assistance with creating a printable calendar using an HTML table. The calendar prints perfectly on a Mac, but when attempted on Windows in all browsers, it adds a 3" margin at the top regardless of CSS print settings. The client requires the cal ...

Square Power Box

I have been attempting to create two equal sections, one displaying an image and the other showing text, both maintaining a square shape with identical width and height. I am using the Avada theme on Wordpress along with Element Builder and custom CSS to a ...

Is there a way to insert data with a specific key into an array of objects without losing existing JSON data in Node.js?

I came across an object structured like this : { "mark": [ { "id":1, "name": "mark", "age":26 }, { "id":2, "name": "mark", " ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

Exploring the method to search across various fields in Vue.js 2

In my Vue.js 2 application, I am attempting to search or filter through three fields: firstname, lastname, and email. Unlike Vue 1, Vue 2 does not include a built-in filter method. As a result, I have created a custom method that can only filter through on ...

Leveraging JavaScript along with the jQuery library and API to showcase information related to

Hey there! I have been working on this API that shows upcoming concerts, but I'm struggling to display the images associated with each concert. I've tried using for loops to iterate through the objects, and it seems like every sixth element has ...

Determining the visible dimensions of an iframe

Is there a way to determine the visual size inside an iframe using JavaScript or jQuery? In this scenario, only a portion of the iframe is displayed. The iframe itself has dimensions of 300x300, but it is being limited by a div to 300x100. <div style= ...

Enhance the functionality of Jquery UI drag and drop to be responsive even when in a zoom

I came across this drag and drop demo for Jquery UI that was working perfectly at a regular zoom level. However, when I zoomed out to 50%, things started acting strange. Can anyone provide suggestions on how to fix the demo? Link to Demo Any help would be ...

Angular Checkbox Binding Issue Detected

Struggling with a problem related to an Angular checkbox form that is generated from an API. I am able to create checkboxes, but encountering two issues: The checked state of the boxes does not align with the values retrieved from the API, and when I clic ...