Script getting executed correctly once page is refreshed - jquery

163 Views Asked by At

In my webpage I have script like this :

<head>
<script src="scripts/effect.js"></script>
<script>
if (document.readyState == 'complete') {
  doOnLoad();
}
$(window).bind("load", doOnLoad);
function doOnLoad() {
    console.log("here..");
}
</script>
</head>

effect.js file contains script as shown below:

$( document ).ready(function(){
    console.log("yes");
   // here I've script for reading a text file using ajax and manipulating the result from text file
    $.ajax({
      // code goes here
      console.log("ajax");
    });
});

The problem is that when I run the page initially, I'm not getting the result. At that time I get console output as

yes
here..
ajax

But when I refresh the page again I am getting the result and console prints like :

yes
ajax
here..

How can I run window.load after the document.ready is completed.

Can anyone help me to fix this? Thanks in advance.

1

There are 1 best solutions below

0
Andrew D On

This is all about the timing of script execution. It sounds like the behaviour is changing once certain resources have been loaded and cached.

The first piece of code you have is a bit confusing:

if (document.readyState == 'complete') {
    doOnLoad();
}

I'm not sure why you need this as well as the on load handler? It looks like that condition is never going to equal true anyway, as that code will run immediately before the document has finished loading. At the very least, I would put a console.log in this block, so I could determine what's triggering doOnLoad.

Try replacing the script on your page for just the following:

$(window).on("load", doOnLoad);
function doOnLoad() {
    console.log("here..");
}