benikens
benikens

Reputation: 163

How to check when Javascript is completed

We are trying to implement some advertising areas into a plugin in wordpress.
For some reason when the plugin calls it's google map js it removes my ads from the page. I can't figure out why that is so instead of digging through their code further we decided on a simpler solution.
I'm now loading the ads into a hidden div above the content area and the moving them into place once the google map is done. At the moment I'm just using setTimeout to achieve this however it would be much better if there was a way to test if the page was properly done loading. Kind of like $(window).load(function(){} except instead of just checking the DOM is done loading be able to check that javascript has finished being executed.

Is there a way to check things like this? Else maybe a way to create an output of all js files being executed so we could actually narrow down where the google map stuff is being done.

Here is our function to display ads:

$( window ).load(function() {
    setTimeout(function(){
      var a = [1,2,3,4];
        a = shuffle(a);
         for (var i = 0; i < 4; i++) {
            if(document.getElementById("mrec"+i)){
              $("#ad"+a[i]).appendTo($("#mrec"+i));
              $("#ad"+a[i]).css({
                  'display': 'block'
              });
            }
         }
    },2500);
});

Upvotes: 0

Views: 334

Answers (1)

denov
denov

Reputation: 12688

if the map plugin returns a value you could wrap it in a promise. http://www.html5rocks.com/en/tutorials/es6/promises/. Dojo has a good support for promises for a long time now. https://dojotoolkit.org/documentation/tutorials/1.10/promises/

but if the plugin doesn't return anything when it completes you do something like

    var howOftenToCheck = 200,
        checkExist = setInterval(function() {
             if(document.getElementById('mapDiv')) {
                 clearInterval(checkExist);
                 // do stuff now that map has loaded
             }
        }, howOftenToCheck);

Upvotes: 1

Related Questions