0
Can some one please explain me what's wrong in this code ! [Solved]
Here is a sample code,I want to display a alert box when the page is fully loaded.so here I'd made it,but when I run the code,it doesn't show the alert box and also it says something in the console.please tell me how to fix this problem... https://code.sololearn.com/WYNTYVKp9Wyy/?ref=app
10 Answers
+ 4
it could be enough, as in fact, minimal delay of setTimeout is around 4/30ms (from memory: I think it is 4, but maybe 30)...
however, for complex page or slow computers, you could increase the value (under 300ms the delay will be unoticeable, and should be enough for majority of pages)...
by the way, a better approach would be to avoid completly alert(), and rather integrate a fake-alert box in the html code (by that way, the page will be rendered at same time as the fake-dialog ;)
+ 3
fully loaded mean DOM was fully builded (and page fully parsed), but that doesn't mean that page has been displayed ;)
+ 2
fixed code:
https://code.sololearn.com/WGBhxFPkMjfB/?ref=app
you just need to call alert with some delay (to let time to display content) inside $(document).ready callback function ;)
+ 2
without a minimal delay, the alert box will pop-up before page was refreshed (even fully loaded) ;)
+ 1
I think you're confused about the .load() method. It does NOT make an event that gets fired when the element is loaded. It requires the first argument to be the url as a string. See here what it does
https://api.jquery.com/load/
Instead, use the .on() method and pass in "load" as the first argument, like so
$(window).on("load", function() {.....})
See .on() method
https://api.jquery.com/on/
After you do that, it still won't alert but the error will be gone. The reason the alert will not show is that after
$(document).ready()
is called, the window would have already loaded. So the 'onload' event of window will never be triggered. To fix it, simply remove the $(window).on('load') event. You don't need it if
$(document).ready()
is already there.
+ 1
(alert, wich is modal windows, block all page execution until closed)
+ 1
visph ok, but the alert() call is inside
$(document).ready()
According to the official docs: https://api.jquery.com/ready/
"Specify a function to execute when the DOM is fully loaded."
which means the alert will be triggered when the DOM is fully loaded right? Or am I missing something here?
+ 1
visph
hmmm that makes sense. I have another question though, is
setTimeout(callback, 0)
guaranteed to be always called after the page is rendered? Because if the page is complex, needs to bring in a lot of assets, or is poorly built, the parsing and then rendering might take more time and as alert() runs asynchronously, the alert could be trigerred before it was intended to.
Thanks a lot for clarifying though👍
0
visph what's the need of setTimeout here? I think
$(document).ready()
is enough here to make the alert trigger at the right time?