Utilizing an Angular framework to access external JavaScript libraries when the document is fully

I'm incorporating a third-party JavaScript library into my .NET Core ASP Angular application. This library executes its functionality within the $(document).ready method. However, I've encountered an issue where the library's logic isn't being applied correctly when navigating to an Angular route because the $(document).ready method isn't triggering.

To address this problem, I have included the external JavaScript library in the scripts section of my angular-cli configuration.

In an attempt to resolve the issue, I edited the third-party JavaScript file and added a method that calls the same logic as the one triggered in the document ready event. Now, I'm facing difficulty figuring out how to invoke this method from my Angular TypeScript component.

To simplify and test the solution, I created a basic JavaScript file named Tester.js, which is listed in my -angular-cli.json under the scripts tag:

(function ($) {
    "use strict";

    $(document).ready(function () {        
        CallMe();
    });

    function CallMe(){
         console.log('HEY I GOT CALLED');
    }

 })(jQuery);

My goal is to trigger the CallMe() method from within a TypeScript component file. While the CallMe() method successfully fires once on the document.ready event, I am struggling to find a way to execute it dynamically from my TypeScript scripts.

Do you have any suggestions or ideas on how to achieve this?

Answer №1

Step 1

Firstly, check the availability of the external library on npm. If it is available there, you can import the desired function instead of making changes to a vendored file.

For instance, it might offer an API like this:
YourTsComponent.ts

const CallMe = require('library').CallMe
// or
import { CallMe } from 'library'

// trigger on route change
CallMe()

If such an option exists, great! If not...

Step 2

Validate your assumption by creating a global variable (attaching CallMe temporarily to window). If your assumption is correct, calling this global variable on route change should produce the desired outcome.

Tester.js

(function($) {
  "use strict";

  $(document).ready(function() {
    CallMe();
  });

  function CallMe() {
    console.log('HEY I GOT CALLED');
  }

  // TODO - remove (testing purpose)
  window._CallMe = CallMe
})(jQuery);

YourTsComponent.ts

// trigger on route change
window._CallMe()

If that doesn't yield results, it's time to reassess your assumption.

However, if it does ...

Step 3

Transform the vendored library into a module that your app can utilize. The process may vary depending on the type of module system you are using. For instance, with require.js:

Tester.js

(function(factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // CommonJS
    factory(require('jquery'));
  } else {
    // Browser globals
    factory(jQuery);
  }
}(function($) {
  "use strict";

  function CallMe() {
    console.log('HEY I GOT CALLED');
  }

  $(document).ready(function() {
    CallMe();
  });

  return CallMe
}));

YourTsComponent.ts

const CallMe = require('/path/to/tester.js')

// trigger on route change
CallMe()

If rewriting a vendored library is not preferable

You could explore overriding the default behavior of .ready so it can be re-executed. There are various answers available here for this approach, but remember, altering jQuery's default behavior carries more risk than modifying a single vendored file.

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

Utilizing JQuery's ajaxComplete method to handle all Ajax requests on the webpage

I am working with a Java Script file and I need to perform an action after each Ajax request/response is completed. However, since I have multiple Ajax requests/responses, I want the action to be triggered only after all of them are completed. $(document) ...

Simply click on a single checkbox in ReactJS

Is there a way to implement a method in which clicking on one checkbox will automatically deselect the other checkboxes, allowing only one selection at a time? import React, { Component } from 'react'; export default class Tablerow extends Comp ...

Angular routing and parameters are not functioning as expected

In my code, I have implemented the following controller: app.controller('ObjectBoardCtrl', ['$scope' , '$rootScope' , '$routeParams' , function($scope , $rootScope, $routeParams) { $scope.selectedObjectId = $ ...

Arrangement of pipe operators in RXJS Angular 5

Do you think my operators are in the correct order? The code snippet below shows that the console logs from the two taps display the same values. Something seems off, right? return this.pcs.getAvailableMaterials(currentProduct.id).pipe( map( ...

How can variables be generated from minimum and maximum values in jQuery?

Trying to establish jQuery variables using minimum and maximum values. To demonstrate what I am attempting to achieve, I have set up this JSFIDDLE Here is the complete code: function findMinMaxValue(selector) { var min=null, max=null; $(".allPro ...

Implementing binding of JSON API responses to dropdown menus in Angular 4

In my current Angular 4 application, I am faced with the challenge of populating a dropdown menu with data from an API response. Specifically, I am struggling to retrieve the necessary information for each section from the API. The API provides data on C ...

Looking to dynamically adjust row color based on status using ANGULAR 4

In my table, I have 6 columns: name, email, phone, company, status_1, and status_2. Both status_1 and status_2 can have two options: "1" or "0." My Requirement: I want to change the color of the row based on the following logic: if(status_1 is "1" ...

The latest update of NextJS, version 13.1.4, encounters issues when implementing SCSS support with the error message "Module next/dist/compiled/sass-loader/fibers.js not

After setting up a new NextJS project, I decided to incorporate SCSS support. The guidelines provided in the documentation seemed straightforward. Following the installation instructions and including an import of SCSS as shown below: import "@/styles ...

Is there a way to transform NextJS typescript files into an intermediate machine-readable format without having to build the entire project?

I need to deliver a Next.js project to my client, but I want to modify the TypeScript files so they are not easily readable by humans. The client will then build and deploy these files to their production environment. How can I achieve this? In summary, C ...

Add a Vue component dynamically before another component within a v-for loop

Seeking advice on how to incorporate an unread component before a dynamic message component within a v-for loop. The goal is to display an unread panel before any unread messages, indicating their status clearly. Below is the sample code without the unrea ...

Issue with drag-and-drop feature conflicting with clicking in Highcharts draggable points

I'm currently using Highcharts version 3.0.7 along with the draggable-points module to enable users to drag points within a displayed series. Users should have the ability to drag a point to move it, as well as click on a point to remove it. The iss ...

Exploring the wonders of Node.js, Redis, and Express.js while navigating through the enchanting world of Asynchronous

Hello there, I must confess that this is a whole new realm for me... Here is what we've got: app.get('/user/:user_id/followings', function(req, res) { var response = {} , userId = req.params.user_id , ids = req.param(' ...

Generating intricate arrays from a given list

If I have an array containing various items like the following: [ ["Core", "Mathematics", "Mathematics 20-4"], ["Core", "Mathematics", "Mathematics 30-1"], ["Other", "Fine Arts", "Art", "some art course"], ["Other", "Fine Arts", "Music", " ...

What is the process for generating Json using information from a form?

Recently, I embarked on a project that involves creating online tours via a form filled out by the administrator. The data submitted through the form is then mapped into a Mongoose Schema and transformed into JSON. In the createcontent.js file, I utilized ...

Encountering a Vue syntax error following the binding of a session variable

Encountering a syntax error while attempting to bind a session variable as a prop of my Vue component. Scrutinizing my code did not reveal any mistakes, but perhaps another set of eyes may catch something. This is where I have registered my components: V ...

Synchronized schedule expiration on Basic Schema

Having some trouble configuring a cron job using the percolate:synced-cron package to expire collection entries based on simple schema date and time fields. Wondering if there is an alternative approach or if something is incorrect in my setup? Encounteri ...

Is my implementation of async await the most efficient method to handle asynchronous operations in my code?

Struggling to implement and grasp async await functions in my login example, I'm uncertain if my code is the most optimal, elegant, and clean. I especially have doubts regarding error handling, and how to best utilize const and functional programming ...

How can JQuery transform this variable into a negative value prior to defining it as a CSS property?

var footerheight = $("footer").height(); $("#body2").css("padding-bottom",footerheight); $("footer").css("margin-top",footerheight); $("footer").css("height",footerheight); $(window).resize(function(){ $("#body2").paddingBottom("auto"); var footerh ...

What is the method for obtaining the socket object for individual users who are connected in Node.js?

I am currently using socket.io to send notifications to users. I have set up a listener that is monitoring for a specific event. myEvent.watch ((res,err)=> { if (!err) { let id = res.userID; let msg = res.msg; //to imple ...

Tips for updating marker information upon clicking in React-leaflet

I am working on a React-leaflet map that displays markers on the left side, while on the right side, there is a list of point names. I want the behavior to be such that when a marker is clicked, the corresponding point name moves to the top of the list. Th ...