Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way of unobtrusive onload in plain javascript

what is the best unobtrusive way of invoking something after the page is being loaded in plain javascript? of course in jquery i would use

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

but i am not sure about the most reliable approach in plain js.

clearly

window.onload = ...

is not proper solution, because it would overwrite previous declaration.

what I am trying to do is to insert an iframe into a div after the page is loaded, but maybe there are actually better ways of doing it. My plan is to do something like

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

EDIT: apologizes for not including all necessary details. The script is not for my website - the idea is to show a part of my site (a form) on external web sites. The priority is to minimize the effort someone has to put to use my code . That is why I would like to keep everything in js file and absolutely nothing in <script> - except of <script src="http://my.website/code.js" />. If I change url of an iframe or i would like to add some features, I would like to update the code on all other web sites without asking them to make any changes.
My approach might be wrong - any suggestions are very welcome.

like image 448
mkk Avatar asked Feb 14 '12 09:02

mkk


1 Answers

//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.

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

Also definitly worth looking at how jQuery does it: http://code.jquery.com/jquery-1.7.js Search for bindReady.

like image 121
osahyoun Avatar answered Oct 20 '22 16:10

osahyoun