What is the difference between these two pieces of code
Sample 1:
<script type="text/javascript">
function myfunc () {
alert('hi');
}
window.onload = myfunc;
</script>
Sample 2:
<script type="text/javascript">
alert('hi');//no function used
</script>
both pieces of code execute successfully.Thanks in advance.
The window.onload
makes it so that all DOM elements are loaded before the script runs - that is, if your script modifies or uses DOM elements, then it should be attached to window.onload
(or something equivalent in a framework). If it is independent of the DOM you can use either. Refer to the Mozilla Developer Network page for more information. Note that inlined scripts that don't run from window.onload
can run once the parser reaches it - it doesn't wait for the rest of the DOM to be loaded.
The first executes after the page completes loading, the other as soon as it is parsed
If you want to see a difference duplicate both code snippets (copy paste twice) and see how they behave
Sample 1 and Sample 2 do the same thing. However, window.onload in Sample 1 executes the function when the HTML content (and all images, stylesheets and remote scripts) are fully loaded (not when all the DOM elements are loaded).
Sample 2 does the same as Sample 1 but executes the script instantly. You will see the difference when you have a page that takes a while to fully load. Your test page might have been basic so that it seemed that they execute at the same time (when in fact window.onload executed after sample 2).
window.onload is normally used when you need to execute Javascript code after the page loaded. The inline script in sample two can be used if you want Javascript to execute INSTANTLY after a particular DOM Element has been loaded in the browser for example.
onload
event triggers when the page has loaded completely including images, audio, etc.
But directly writing a statement will execute instantaneously.
Hence, onload alert will trigger after the other one.
Check this DEMO
Another important difference is that , since the second script executes immediately , You won't be able to access any DOM elements which comes after that script.
For example if you have a DIV element just before the ending of the tag , you cannot use document.getElementById ( or similar DOM accessing function ) to get that particular DIV.
But with the first script, which will be executed only after the page load , You can access any element in the DOM