It's all about HTML tags elements and execution time. In your example, the script is positioned in the head tag, so when the script is executed, the element div#timer does not exists at all.
Then you have 2 solutions:
If your DOM is not complex, and does not contains img
tags or any kind of elements that need to be fetched from the network, the use of onload
is not needed. You can use it in two cases:
- you have to wait for all elements to be loaded, like images, videos etc,
- you want to delay the execution of a low-priority script, like a script to load ads on your site for example. This script is not vital for your website and your visitor, the execution can be delayed
In general, is it considered as a good practice to put script
tags at the end of the document (and so you don't need to use onload
), it prevents the Flash Of Unstyled Content (FOUC). Javascript blocks your browser rendering engine. So if JavaScript tags are place before the content becomes available to the user (read: in the head tag), the browser will executed it, the DOM being almost empty, and the user will only see a blank page during this execution time.
Also, about jQuery.fn.ready
method, you have to be aware of this:
$(document).ready(function() {
// my first useless function
console.log( "first", 1 );
});
$(document).ready(function() {
// my second useless function
// this function will throw an (intentional) error
console.log( "second", someUndefinedVariable );
});
$(document).ready(function() {
// my third useless function
// because the previous function contains an error
// this function will never be called
console.log( "third ", 3 );
});
So let's say you're using some plugins, and you've some hand-written code and so on. If every plugin and your code is using the jQuery.fn.ready
method, and if for some reason (let's say in some specific browser version under some circumstances) a function throw an error, then all handler after this function would be never runt...
Also, doing so, you're delaying all the "real" JavaScript execution at the end, and if you've a lot of methods to run in the queue, then you could blocks the browser during some seconds, and the user will notify it.