Is there a proper/standard way?
<a href="#" onclick="function();">Link</a>
vs
<script>
$(document).ready(function(){
$('#link1').click(function(){ ... });
});
</script>
<a href="#" id="link1">Link</a>
The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
The only reason people used window. onload is because they mistakenly believed scripts needed to go in the head section. Because things are executed in order if your script was in the head section then the body and your content didn't yet exist by definition of execute in order.
Differences. The DOMContentLoaded event fires when all the nodes in the page have been constructed in the DOM tree. The load event fires when all resources such as images and sub-frames are loaded completely.
The window. onload event gets fired when all resources - including images, external script, CSS - of a page have been loaded. If you want to do something when that event has been fired you should always use the window.
Personally I prefer the second. It allows me to separate my markup and script. This means that scripts could be placed in a separate file and since scripts are static resources they get cached, minified, obfuscated, ... And reduced markup size obviously leads to reduced bandwidth and so faster loading site. In a web page there are really 3 notions that should not be mixed:
From the top of my head:
You would use the first one when... ask facebook or hotmail. I've got nothing on that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With