Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a function when page has fully loaded?

Tags:

javascript

I need to execute some JavaScript code when the page has fully loaded. This includes things like images.

I know you can check if the DOM is ready, but I don’t know if this is the same as when the page is fully loaded.

like image 285
Ben Shelock Avatar asked Jun 23 '09 15:06

Ben Shelock


People also ask

How do I run a function after the page is loaded?

same for jQuery: $(document). ready(function() { //same as: $(function() { alert("hi 1"); }); $(window). load(function() { alert("hi 2"); });

What event do you use to perform something after the page has finished loading?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

How do you make a function fire on a page load?

You have to call the function you want to be called on load (i.e., load of the document/page). For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document.


2 Answers

That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.

window.addEventListener('load', function () {   alert("It's loaded!") }) 
like image 75
Matchu Avatar answered Sep 30 '22 03:09

Matchu


Usually you can use window.onload, but you may notice that recent browsers don't fire window.onload when you use the back/forward history buttons.

Some people suggest weird contortions to work around this problem, but really if you just make a window.onunload handler (even one that doesn't do anything), this caching behavior will be disabled in all browsers. The MDC documents this "feature" pretty well, but for some reason there are still people using setInterval and other weird hacks.

Some versions of Opera have a bug that can be worked around by adding the following somewhere in your page:

<script>history.navigationMode = 'compatible';</script> 

If you're just trying to get a javascript function called once per-view (and not necessarily after the DOM is finished loading), you can do something like this:

<img src="javascript:location.href='javascript:yourFunction();';"> 

For example, I use this trick to preload a very large file into the cache on a loading screen:

<img src="bigfile" onload="this.location.href='javascript:location.href=\'javascript:doredir();\';';doredir();"> 
like image 27
geocar Avatar answered Sep 30 '22 02:09

geocar