1

Is it possible to run javascript function after external asynchronous script was loaded?

After example.js runs (async. it seems), this is the result:

<div class="keepthisdiv">Keep this text</div>
<div class="removethisdiv">Remove this text</div>
<div class="keepthisdiv">Keep this text</div>

Example.js has to be run between body tags, if it's in the head, there is no output.

Here is my div container and js code (credits):

<div id="jscontainer"></div>

<script>

function loadBackupScript(callback){
    if (typeof callback !== 'function') {
       throw 'Not a valid callback';  
    }
    var script = document.createElement('script');
    script.onload = callback;  
    script.src = 'http://www.example.com/example.js';
    script.type = 'text/javascript';
    var container = document.getElementById("jscontainer");
    container.appendChild(script);
}

loadBackupScript(function() {

$( ".removethisdiv" ).remove();

});

</script>

However, it doesn't remove a div with removethisdiv class. loadBackupScript obviously runs before example.js is completely parsed.

How can I run loadBackupScript function right after removethisdiv class is inserted into DOM? I know that it is possible to use a timer and then remove it after few seconds, but it is unreliable, because external script's parsing times vary. Also, there are many different scripts on the same page, so I'd like to avoid waiting for page to load completely and I need to specifically target this script (example.js).

9
  • If example.js is yours - do it in there?
    – user1017882
    Sep 22, 2015 at 12:50
  • loadBackupScript obviously runs before example.js is completely parsed Why? it shouldn't be like this, load event is fired after the script is loaded and parsed. Sep 22, 2015 at 13:10
  • @JayMee It's external script, I don't have any control over it.
    – take2
    Sep 22, 2015 at 13:19
  • 1
    You are missing a very basic concept: loaded and parsed are not different in javascript. Once a script is loaded you are guaranteed it has also been parsed and executed, if then your script starts other async operations, that's another story. Sep 22, 2015 at 13:39
  • 1
    There is no magic bullet for this. You have to examine your external script, understand which async tasks is performing and execute your callback when they are completed. If you can't modify the external script, you could setup some polling with setInterval on variables or DOM elements the external script is going to change. Anyway why would you do this? Try to explain what you need to achieve and maybe we can suggest a more proper way of doing that. Sep 22, 2015 at 14:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.