The best way to unobtrusively load in plain javascript

What is the best unobtrusive way to call something after loading a page in plain javascript? of course in jquery i would use

$(document).ready(function(){...});

but I'm not sure about the most reliable approach in simple js.

clear

window.onload = ...

This is not the right decision, as it overwrites the previous ad.

what I'm trying to do is insert an iframe into the div after the page loads, but maybe there are better ways to do this. My plan is to do something like

window.onload = function(divId){
 var div = document.getElementById(divId);
 div.innerHTML = "<iframe src='someUrl' .. >";
}

EDIT: . script - , () -. , , - . js <script> - <script src="http://my.website/code.js" />. url iframe , -, - .
- .

+5
3
//For modern browsers:
document.addEventListener( "DOMContentLoaded", someFunction, false );

//For IE:
document.attachEvent( "onreadystatechange", someFunction);

`attachEvent` and `addEventListener` allow you to register more than one event listener for a particular target.

: https://developer.mozilla.org/en/DOM/element.addEventListener

, jQuery: http://code.jquery.com/jquery-1.7.js bindReady.

+7

script </body>, :

(content)
(content)
<script src="http://my.website/code.js"></script>
</body>
</html>

script DOM (). , ( ..) , , -, window load ( ).

ready -style , , script (, ), - - , HTTP- (, , ).

+2

window.addEventListener load DOMContentLoaded:

window.addEventListener('DOMContentLoaded',function(){alert("first handler");});
window.addEventListener('DOMContentLoaded',function(){alert("second handler");});

object.addEventListener('event',callback) . . https://developer.mozilla.org/en/DOM/element.addEventListener.

IE5-8 window.attachEvent('event',callback), . http://msdn.microsoft.com/en-us/library/ms536343%28VS.85%29.aspx. :

function addEventHandler(object,szEvent,cbCallback){
    if(typeof(szEvent) !== 'string' || typeof(cbCallback) !== 'function')
        return false;
    if(!!object.addEventListener){ // for IE9+
        return object.addEventListener(szEvent,cbCallback);
    }
    if(!!object.attachEvent){ // for IE <=8
        return object.attachEvent(szEvent,cbCallback);
    }
    return false;
}
addEventHandler(window,'load',function(){alert("first handler");});
addEventHandler(window,'load',function(){alert("second handler");});

Note that it is DOMContentLoadednot defined in IE lesser 9. If you do not know that your destination browser is using the event load.

+2
source

All Articles