1

I have an external javascript file that I only want to be included on a particular component, so I am loading it dynamically. This answer describes how to do that.

However, the javscript file I'm using does some stuff on window.load:

$(window).on('load', function() {
    //Some logic
});

Because I'm loading this script dynamically for a specific component, this logic is never firing because the load event fired long before the script was loaded. How can I execute this logic after I've loaded the script?

Narm
  • 10,677
  • 5
  • 41
  • 54
user522048
  • 61
  • 1
  • 3

1 Answers1

1

You'll have to fire the window.load event after you load the script. The only problem is this might have side effects from scripts that bind to this event and (rightly) do anticipate the event occurring multiple times.

const evt = document.createEvent('Event');  
evt.initEvent('load', true, true);  
window.dispatchEvent(evt);

Alternatively and since you seem to have intimate knowledge on how this script works, you might consider recreating the code the occurs after the window loads. This should mitigate the side effects caused by re-firing the load event.

Either solution is hacky. Probably the best solution is to consider using a different component. One that doesn't have dependencies on other frameworks or was written for Angular.

Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70