Boa
Boa

Reputation: 2677

Removing a DOM element from an element which is generated by an external script

Within a page, I have third-party ad content that is generated by an external script. This content takes a little while to load. I would like to remove a line break from the ad content - to do so, it's necessary to wait until the external script has loaded and all of the functions called within that script have stopped running. I was tinkering with the following idea, but I guess it only waits until the external script is loaded:

$.getScript( "http://www.external_site.com/widget.js").done( function(data, textStatus, jqxhr) {
     $('.result').find('br').remove();  
});

What's the best way to wait until the external script performs all of its DOM manipulations, before calling the .remove() function?

Upvotes: 4

Views: 1029

Answers (1)

David Thomas
David Thomas

Reputation: 253318

One approach seems to be listening for the onreadystatechange and load events being fired from the newly-created and inserted <script> elements, in which the JavaScript is run.

This works in the linked (simple) demo, but I can't attest to its reliability for large projects:

// listening for the onreadystatechange and/or load
// events fired from the newly-added "script" elements:
$('script').on('onreadystatechange load', function (e) {
    // performs the following simple/contrived functionality:
    $('body').find('br').remove();
});

JS Fiddle demo.

References:

Upvotes: 4

Related Questions