Document ready and load

I want the same script to run when the document first loads and again when the document is ready … which means , when i first visit the website , the script should run and when i again refresh the website the same script should again run

Like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Whatever</title>
</head>
<body>
  
  <!- Your script here -->
  <script src="index.js"></script>
</body>
</html>
1 Like

its not that easy bruh… ill attach the code…actually ajax and jquery are involved …its a javascript thing that
$(document).load(function(){ sample code});
$(document).ready(function(){ sample code}).
both the sample codes being the same

window.onload fires later than $(document).ready. ready fires when all of the HTML has been parsed and loaded, and onload fires when all of the content has been loaded to the viewport. (images, etc)
It should be noted that

$(document).load()

is NOT equivalent to

window.onload()

and is NOT equivalent to

document.onload()

the first is a jQuery function, NOT an event handler.
the second is the proper event handler for when the content has fully loaded.
the third is equivilant to $(document).ready().

You could extract the code in a function then:

var sampleCode = function () {/* ... */}

$(window).load(sampleCode)
$(document).ready(sampleCode)

However, that code would then always run twice (regardless if the page is being visited the first time or being refreshed). As @James_Hibbard said, you’re usually fine with just putting your code at the end of the body; only if you need to wait for images etc. being completely loaded, use $(window).load().

(Except dont use $(window).load() because that’s not an event handler…) [using .load() as an event handler was deprecated and removed in jquery 1.8, and is now an entirely different thing. Which is a silly thing to do, I know, but… such is what it is.]

1 Like

Interesting… I didn’t quite get it from your previous comment TBH. Thanks for pointing that out! :-)

I can’t run this method on my site. Have you another solutions?

Unless a page fails to load - which would be a more serious and unrelated problem - I can’t think of any reason why the event might not propagate so that it couldn’t be detected.

Please explain the “why” you can’t use the methods.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.