Using Angular: Dynamically load an external JavaScript file after the Component View has finished loading

In my Angular 5 application, I am faced with the challenge of loading a JavaScript script file dynamically after my component view has been fully loaded.

This script is closely related to my component template, requiring the view to be loaded before it can properly execute.

I have attempted the following approach:

export class MyComponent implements AfterViewInit{
   title = 'app';
   ngAfterViewInit() {
     this.loadScript('http://www.some-library.com/library.js');
     // OR THIS
     this.loadScript('../assets/js/my-library.js');
   }
  }

  public loadScript(url: string) {
    const body = <HTMLDivElement> document.body;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }
}

However, the issue persists as the JavaScript file is still loaded before the component HTML file, resulting in the script not functioning as intended.

(Even though it appears in the body, it does not work as expected)

The primary goal is to ensure that my JavaScript file is loaded after my component is fully loaded.

Any suggestions on how to achieve this?

Answer №1

Implement the AfterContentChecked LifeCycle method.

AfterContent hooks The AfterContent hooks work similarly to AfterView hooks but focus on the child component.

-The AfterView hooks are related to ViewChildren, the child components within the template of the component.

-The AfterContent hooks are related to ContentChildren, the child components projected into the component by Angular.

Alternatively:

A different way that worked for me was:

ngAfterViewInit() {
    setTimeout(() => {
        doSomething();
    }, 0);
}

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

Avoiding server requests in Firefox by refraining from using ajax

I've implemented the following jquery code: $("#tasksViewType").selectBox().change( function (){ var userId = $('#hiddenUserId').val(); var viewTypeId = $("#tasksViewType").val(); $.post('updateViewType& ...

Find an element within an array in a separate JavaScript file (leveraging AngularJS)

I am new to AngularJS and decided to create a custom map with my own markers that I defined. To do this, I started by creating a JavaScript file containing an array: var myMarkers=[{ method1='..', methode2='..' },{ method1=&a ...

Using Vue to append elements that are not part of the loop

While looping over a table row, I realized that each of the table rows should be accompanied by another table row containing additional data from the loop. Unfortunately, I am struggling to insert <tr class="data-spacer"></tr> <tr& ...

The keyboard automatically disappeared upon clicking the select2 input

Whenever I select the select2 input, the keyboard automatically closes $('select').on('select2:open', function(e) { $('.select2-search input').prop('focus',false); }); Feel free to watch this video for more i ...

io-ts: Defining mandatory and optional keys within an object using a literal union

I am currently in the process of defining a new codec using io-ts. Once completed, I want the structure to resemble the following: type General = unknown; type SupportedEnv = 'required' | 'optional' type Supported = { required: Gene ...

Using API calls to update component state in React-Redux

I am currently working on setting up a React application where clicking on a map marker in one component triggers the re-rendering of another component on the page. This new component should display data retrieved from a database and update the URL accordi ...

Challenges encountered when inserting nested data into MongoDB

I am currently in the process of constructing a database for a giveaway bot using MongoDB. When a new giveaway is initiated, the bot executes the following code to add the giveaway details to the database: const {mongoose} = require("mongoose") c ...

React allows for items to be exchanged between two lists

I am currently working on a functionality that involves swapping items between two arrays. The user interacts with two lists in the UI by selecting items from the first list, which should then be removed from there and added to the second list where the se ...

angular 6's distinctUntilChanged() function is not producing the desired results

I have a function that retrieves an observable like so: constructor(private _http: HttpClient) {} getUsers(location){ return this._http.get(`https://someurl?location=${location}`) .pipe( map((response: any) => response), ...

React application experiencing freezing when setInterval function is utilized

I've been working on incorporating Conway's Game of Life into a React project, but I'm encountering freezing issues whenever a new generation is triggered. My assumption is that the problem lies in the excessive overhead from constant DOM re ...

Unresponsive Textbox Input Issue within Reactive Form

My current setup involves an Angular Reactive Form with various controls: this.taskForm = this.formBuilder.group({ storyNumber: new FormControl('', [Validators.required, Validators.pattern('^[A-Z]{2,}[0-9]*-[0-9]{2,}$')]), ...

What is the best choice for storing data in my Angular2+ component: an object or an observable?

If I were to create an angular2+ component that fetches data from an API and displays its name, which approach would be considered more idiomatic? Initial Strategy: Using thing as an object In this scenario, the component subscribes to a websocket observ ...

Sorting and selecting isotopes, with the option to filter or unfilter

All day I've been struggling to find a solution for my isotope filtering issue. I'm using classes from the database to tag items, such as categories and dates, and allowing users to filter them. The tricky part is making these filters work like o ...

Error: Unable to connect to 'ngbTypeahead' as it is not recognized as a valid attribute of 'input' in the template

Having trouble with ngbTypeahead. The console is displaying the following error message: Error: Template parse errors: Can't bind to 'ngbTypeahead' since it isn't a known property of 'input'. (" <inpu ...

Utilizing JavascriptExecutor in Selenium Webdriver to start playing a video

Is it possible to trigger the play function in a page's JavaScript jQuery code using JavascriptExecutor? Below is an example of code extracted from a website: <script type="text/javascript"> jQuery(document).ready(function($) { $('#wp_mep ...

encasing a snippet of code within a customized hyperlink

Here's the following "embed code" for an Instagram photo featuring Kim Kardashian. I'm curious - how can one encapsulate this embed code within an <a> tag (or another tag) so that clicking on the image will redirect to www.google.com? < ...

Discover the secrets to acquiring cookies within a Next.js environment

I am currently working with Next.js and attempting to retrieve a cookie value. Below is the code I have written: import cookie from "js-cookie"; export default function Home({ token }) { return ( <div className="flex flex-col items ...

Make sure that the webpage does not display any content until the stylesheet has been fully loaded by

I am seeking to utilize ng-href for loading different Themes. One issue I am encountering is that the unstyled content appears before the stylesheet is applied. I have created a Plunker where I made changes to Line 8 in the last 3 Versions for comparison ...

How to Convert Python Lists into JavaScript?

octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random. ...

`Can you explain how to specify the elements of an array within a form using AngularJS?`

Below is an array containing objects: //Data source code $scope.data = [ { name: 'Lname', items: [{ label: 'Lastname', type: 'text', model: 'lname', pattern: '/^[a-zA-Z]$/', ...