Is "onload" required when the code is below?

I was wondering if window.onload = function(){}(or any other kind of onload like jQuery is needed $(document).ready();if the code is at the bottom of mine <body>?

Or could there be unexpected side effects?

+5
source share
3 answers

Yes, there may be unexpected consequences. But no, this is not entirely necessary. Time can be turned off for things that are still loading, such as complex layouts, deep DOM structures, dynamic HTML from other scripts or images. To avoid these situations, it is always safe to wrap your script in an event onload.

, . Chrome 17.0.963.12 dev OS X. , onload, . fail, (.. , ) success, . onload success.

1

, . onload, , - .

: http://jsfiddle.net/ThinkingStiff/qUWxX/

HTML:

<div id="result"></div>
<img id='image' src="http://thinkingstiff.com/images/matt.jpg" />

Script:

document.getElementById( 'result' ).innerHTML 
    = document.getElementById( 'image' ).offsetWidth == 346 ? 'success': 'fail';

, jsFiddle onLoad , - success.

enter image description here

"onDomReady" "no wrap (body)":

enter image description hereenter image description here

"" :

enter image description here

fail.

2

, . HTML script. , , ​​ script. onload corrent, , . , , .

: http://jsfiddle.net/ThinkingStiff/n7GWt/

HTML:

<div id="result"></div>
<div id="style"></div>

<script>
    window.setTimeout( function() { 
        document.getElementById( 'style' ).style.width = '100px'; 
    }, 1 );
</script>

Script:

document.getElementById( 'result' ).innerHTML 
    = document.getElementById( 'style' ).style.width ? 'success' : 'fail';

3

, Javascript , CSS. , onload .

: http://jsfiddle.net/ThinkingStiff/HN2bH/

CSS

#style {
    animation:             style 5s infinite;
        -moz-animation:    style 5s infinite;
        -ms-animation:     style 5s infinite;
        -o-animation:      style 5s infinite;
        -webkit-animation: style 5s infinite;
    border: 1px solid black;
    height: 20px;
    width: 100px;    
}

@keyframes             style { 0% { width: 100px; } 100% { width: 500px; } }
    @-moz-keyframes    style { 0% { width: 100px; } 100% { width: 500px; } }
    @-ms-keyframes     style { 0% { width: 100px; } 100% { width: 500px; } }
    @-o-keyframes      style { 0% { width: 100px; } 100% { width: 500px; } }
    @-webkit-keyframes style { 0% { width: 100px; } 100% { width: 500px; } }

HTML:

<div id="result"></div>
<div id="style"></div>

Script:

document.getElementById( 'result' ).innerHTML 
    = document.getElementById( 'style' ).clientWidth > 100 ? 'success' : 'fail';

, , . , script onload.

+6

.

  • onload , , . , onload, , .
  • , DOM (.. ) . , , , - , , .

, , , getElementById, , . . , - .

+2

The script tag at the bottom of the HTML page is equivalent DOMContentLoaded. All html codes have been loaded, and Javascript can now access DOM elements.

load called when all other resources, such as images, are fully loaded.

+1
source

All Articles