简体   繁体   中英

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM