0

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!

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.