Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Detect when a window is fully loaded

I have a script which may be loaded at any stage of the life cycle of a web page. When the script is loaded it must run an initialize() method.

I want this function to be run on the "onload" event, but I cannot be certain that the page has not already loaded, i.e. that the "onload" has not been fired already.

Ideally my script would look like this:

var _initialize = function() { ...};

if(window.LOADED)
    _initialize();
else if (window.addEventListener)
    window.addEventListener('load', _initialize, false); 
else if (window.attachEvent)
    window.attachEvent('onload', _initialize);

Is there any such window.LOADED or document.LOADED variable or something similar?

Thanks in advance, Shane

like image 411
Shane Avatar asked Jun 21 '11 10:06

Shane


People also ask

How do I check if a website is fully loaded in JavaScript?

After you have a basic understanding of javascript, you can detect when a page has loaded by using the window. onload event. window. onload = function() { addPageContents(); //example function call. }

Which event occurs when page has been loaded?

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded , which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. This event is not cancelable and does not bubble.

How do I check DOM Content Loaded?

If you want to know "exactly" if DOMContentLoaded was fired, you could use a boolean flag like this: var loaded=false; document. addEventListener('DOMContentLoaded',function(){ loaded=true; ... } Nice try :).

What is DOMContentLoaded used for?

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A different event, load , should be used only to detect a fully-loaded page.


1 Answers

You can use jQuery to do this. $(document).ready(). Check this

Just call the function you want inside the ready. Then it'll be executed once the document is fully loaded

like image 72
Balanivash Avatar answered Oct 04 '22 06:10

Balanivash