Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript alert loads before page displays

On my mobile, in safari If I go to my default page that has alert("Hello") on the body onload event, the alert displays with my default page fully visible in the background. If I then go to another site for example bbc.co.uk and then type in my the web address for my default page in the address bar, the alert shows with the BBC content in the background, its like the alert loads before the page has loaded.

How do I only show the message once the whole page is visible. I've read that window.onload waits until everything is loaded before it triggers the alert but I must be getting something wrong because the behaviour doesn't change. I've also tried:

$(document).ready(function () {
    window.onload= alert('Test');
});

and

<meta http-equiv="Pragma" content="no-cache"/>

in case it has something to do with cache but I don't think this is the issue. Any ideas ?

Thanks

like image 690
mjroodt Avatar asked Sep 05 '12 11:09

mjroodt


2 Answers

You pass a reference to a function to the window.onload and not the actual call.

try

window.onload = function(){
 alert('test');
}
like image 55
Clyde Lobo Avatar answered Sep 21 '22 07:09

Clyde Lobo


if you wanto display the alrert box either use window.onload there is no point in use both , here is code that will work fine

window.onload (which is implemented even in old browsers), which fires when the entire page loads

 window.onload = function(){  alert('test'); } 

jQuery provides document.ready, which abstracts those away, and fires as soon as the page's DOM is ready

$(document).ready(function () {     
 alert('Test');  
});

Check answer from : window.onload vs $(document).ready()

window.onload is the built-in Javascript event, but as its implementation had subtle quirks across browsers (FF/IE6/IE8/Opera), jQuery provides document.ready, which abstracts those away, and fires as soon as the page's DOM is ready (doesn't wait for images etc.).

document.ready is a jQuery function, wrapping and providing consistency to the following events:

  • document.ondomcontentready / document.ondomcontentloaded - a newish event which fires when the document's DOM is loaded (which may be some time before the images etc. are loaded); again, slightly different in IE and in rest of the world
  • and window.onload (which is implemented even in old browsers), which fires when the entire page loads (images, styles, etc.)
like image 23
Pranay Rana Avatar answered Sep 22 '22 07:09

Pranay Rana