Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS not working on first load - works after a refresh

I'm doing a fairly simply thing in JS: I'm testing if an element (based on a Class Name) contains a string.

I think the reason it's not working is because the element is rendered on the page via a HTTPS request separate to the onload event. (Sort of like an embedded/iFrame type thing).

Example of the script that I have:

(function($) {

//Only run on a specific page.
if(window.location.href.indexOf("SpecificPageImRunningOn") > -1) {

    //Wait for 3 seconds before running this script, to allow content to load
    setTimeout(function(){

        //Check if a class contains a string "Foobar"
        if($('.aSpecificClass').text().indexOf('Foobar') != -1){
            alert("Yes!");
        }
        else{
            alert("No!");
        }

    }, 3000);

}

})(jQuery);

When I test this the first time round (fresh browser- cleared cache), it does not work as expected.

Once I refresh, it works perfectly well.

I have tried triggering the function manually (via clicking a button after everything has loaded) and it still did not behave any differently. It did not work at all on the first load.

I have also tried doing a single forced refresh by setting a cookie and that did not seem to make any difference.

I think I'm missing something obvious!

Test

like image 549
Tim Avatar asked Nov 24 '16 13:11

Tim


1 Answers

You shouldn't rely on a timeout to wait for an element to become ready. The first time you run it, the element is not ready at the time, while the second time it is because it was cached after the first run.

Either put the script at the bottom of the page, before you close the body tag, or use $(document).ready() callback to run once once DOM is ready.

like image 198
Shomz Avatar answered Sep 23 '22 06:09

Shomz