So i am reading the height of an element using .offsetHeight within a window.onload listener. This means that the html elements must have loaded. However, if i use the same code but instead of using the window.onload i use a setTimeout with a 100ms wait time, the offsetHeight is different (which appears to be the correct value). Why is this? I obviously don't want to be adding unnecessary load times onto my web pages, are there any work arounds?
P.s even when using a 50ms wait time the results are inconsistent.
Thanks in advance.
I submitted my HTML5 game for a HTML5 game platform for QA review and got the following feedback:
You should not perform time consuming tasks before window.onload but the actual is: DOM is blocked.
I am not sure what this review means. What I am doing now is:
$(window).ready(
....
);
So this is the entry point of all the code. So what is the difference between $(window).ready and $(document).ready() and window.onload. Do they follow a fixed order as to when they are triggered? And what does DOM is blocked mean?
dom ready vs window.load
$(document).ready(function(){}); is triggered until the HTML is fully parsed and rendered, but before all Assets (images, iframes and so on) are downloaded. $(window).load is executed right after all images are downloaded.
This means: $(document).ready comes always before $(window).load.
DOM is blocked
Is quite untechnical and not really the truth. You showcase, that you can manipulate the DOM at "DOM ready" and acutally this is the right event for doing so. What they mean is the following: As long as a script is executing, the browsers main thread is blocked. Which means, that the browser can not render/paint anything in this time and the browser becomes unresponsive.
The idea behind this advice is the following:
If you are executing a script on DOM ready, painting stops and will be delayed after script execution. The user might see some sort of your UI, because at this time the DOM is already rendered and in most cases also the CSS is, but not the images. But if you delay it after window.onload the browser can also render images and iframes, before you block the main thread, which means the user might see a fully rendered site/game sooner, although it isn't technically ready yet.
My 2 cents
Wether this is a good approach or not, really depends on a lot of circumstances. If your JS does a lot of UI things, it is bad, because the user won't see the final UI sooner, the user will see it later. If your JS is important for the page to work and the page has some bigger images, it is quite stupid to delay executing script. Consider a mobile user, he might already see the UI to start the game, but your click/tap event isn't yet bound, because there is a big image at the end of your page, which still needs to load?
If you have a performance problem fix it, don't delay it to antoher point, this will also block the main thread. But what you can do: If you have a lot of scripts, you can split those tasks into chunks and execute them at the point, when they are really needed and not initially. For example: You have a Menu and this menu has a hidden sub menu, which needs initially some special dom manipulation. Don't do this at dom ready or on window.load, do it right before it opens for the first time.
Might seem like a trivial question but I've run into an issue while using jQuery. When I try and get the height for an element within a .ready I am always given zero.
$(function() {
$('#my-elem').height() // Always gives me zero.
});
If I put code in a delay with setTimeout() around the height check (say of .5s) then the height is correctly reported back to me. I'm guessing that this is because the styles haven't had a chance to be applied yet?
The only solution I've found to this problem is to use an interval to poll the height of the element until it becomes non-zero but this seems overkill to me. Is there a better way?
The document.ready event signals that the HTML DOM is ready for accessing via Javascript, but that doesn't mean that the elements have already rendered.
In fact, that's the whole shebang behind ready: it's a means for you to start manipulating your document's HTML DOM without having to wait for the page to finish loading. It's safe to assume that at document.ready, your elements are not yet displayed on the page.
Now, that comes with a caveat: if the elements haven't rendered yet, how can the browser / Javascript know what its resolving height is? .height() may give zero at document.ready because of this. It's probably best to wait until load instead of ready when it comes to pulling box dimensions from the layout.
You can see whats happening here..
http://jsfiddle.net/gregguida/36SEZ/4/
Switch tabs for about 30 seconds and then come back, the animation gets totally out of hand.
I think this has something to do with the way the browser treats setInteval() when the window doesn't have focus but I'm not sure if that's the case. I also don't know what to do about it. Any insight is appreciated.
Update: also tried using setTimeout instead of setInterval but I'm experiancing similar results
Thanks!
I ran into the same when creating an animation for my site. The way I got around it was by removing the call to setInterval and setting a new timeout each time the animation is completed.
Here is your code updated to use that approach: http://jsfiddle.net/36SEZ/5/
Note that the call to setTimeout should be called only once after all of the animation is finished. In order to make sure that happens I've put it in the complete function of the last animation on the last div.
You should read the second note at http://api.jquery.com/animate/#notes-0
I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).
Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?
For example:
function updateDOM(id) {
// updates the id element based on form state
}
should I invoke it via:
window.onload = function() { updateDOM("myElement"); };
or:
<div id="myElement">...</div>
<script language="javascript">
updateDOM("myElement");
</script>
The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.
Any thoughts? Is one version really better than the other?
The onload event is considered the proper way to do it, but if you don't mind using a javascript library, jQuery's $(document).ready() is even better.
$(document).ready(function(){
// manipulate the DOM all you want here
});
The advantages are:
Call $(document).ready() as many times as you want to register additional code to run - you can only set window.onload once.
$(document).ready() actions happen as soon as the DOM is complete - window.onload has to wait for images and such.
I hope I'm not becoming The Guy Who Suggests jQuery On Every JavaScript Question, but it really is great.
I've written lots of Javascript and window.onload is a terrible way to do it. It is brittle and waits until every asset of the page has loaded. So if one image takes forever or a resource doesn't timeout until 30 seconds, your code will not run before the user can see/manipulate the page.
Also, if another piece of Javascript decides to use window.onload = function() {}, your code will be blown away.
The proper way to run your code when the page is ready is wait for the element you need to change is ready/available. Many JS libraries have this as built-in functionality.
Check out:
http://docs.jquery.com/Events/ready#fn
http://developer.yahoo.com/yui/event/#onavailable
Definitely use onload. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.
Some JavaScript frameworks, such as mootools, give you access to a special event named "domready":
Contains the window Event 'domready', which will execute when the DOM has loaded. To ensure that DOM elements exist when the code attempting to access them is executed, they should be placed within the 'domready' event.
window.addEvent('domready', function() {
alert("The DOM is ready.");
});
window.onload on IE waits for the binary information to load also. It isn't a strict definition of "when the DOM is loaded". So there can be significant lag between when the page is perceived to be loaded and when your script gets fired. Because of this I would recommend looking into one of the plentiful JS frameworks (prototype/jQuery) to handle the heavy lifting for you.
#The Geek
I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).
In Firefox, onload is called when the DOM has finished loading regardless of how you navigated to a page.
While I agree with the others about using window.onload if possible for clean code, I'm pretty sure that window.onload will be called again when a user hits the back button in IE, but doesn't get called again in Firefox. (Unless they changed it recently).
Edit: I could have that backwards.
In some cases, it's necessary to use inline script when you want your script to be evaluated when the user hits the back button from another page, back to your page.
Any corrections or additions to this answer are welcome... I'm not a javascript expert.
My take is the former becauase you can only have 1 window.onload function, while inline script blocks you have an n number.
onLoad because it is far easier to tell what code runs when the page loads up than having to read down through scads of html looking for script tags that might execute.