Lio
Lio

Reputation: 1503

How to call function when async Javascript file is loaded?

I'm having a little trouble with calling function after including/loading 3rd party widget on my web-site.

Consider this scenario. I load a script, which generates widget from 3rd party library like this.

<script>
var element= document.createElement("script");
element.src = 'http://example.com/script.js';
document.body.appendChild(element);
</script>

After finishing loading it then creates #someElement div tag, which has style attribute with some rules and appends it to body element.

What I want to do, is to remove that style attribute and add some CSS class.

So, the question is, how can I check, when that file is loaded, or that element created and call my function after that?

Thank you!

Upvotes: 0

Views: 1536

Answers (1)

gaurav5430
gaurav5430

Reputation: 13892

To check if the script has loaded or not:

If the script creates any variables or functions in the global space you can check for their existance:

External JS (in global scope) --

var myCustomFlag = true;

And to check if this has run:

if (typeof window.myCustomFlag == 'undefined') {
    //the flag was not found, so the code has not run
    $.getScript('<external JS>');
}

You can check for the existence of the tag in question by selecting all of the elements and checking their src attributes:

//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
    return ($(this).attr('src') == '<external JS>');
}).length;

//if there are no scripts that match, the load it
if (len === 0) {
    $.getScript('<external JS>');
}Or you can just bake this .filter() functionality right into the selector:

var len = $('script[src="<external JS>"]').length;

for further discussion. see : Verify External Script Is Loaded

Upvotes: 1

Related Questions