I have a javascript code like this
<script type="text/javascript">
window.onload=myFunction;
</script>
Is there any difference in using the above snippet in the <head></head> tag and just before
</body> tag, as I would like to call my function after the page loads.
Binding to
window.onloadwill always run your function when theloadevent fires. This only fires after everything in the page has finished loading, including images etc. If you want to run your function when the DOM has finished loading but before everything else then you can bind to theDOMContentLoadedevent or use a library like jQuery (e.g.$(function(){ myFunction() });).The benefit about putting your function at the end of your
<body>is that theoretically this means that the rest of your content has already loaded and you don’t need to bind your function to aloadevent. This sometimes works, but depends on the situation.