I'm executing an external script, using a <script>
inside <head>
.
Now since the script executes before the page has loaded, I can't access the <body>
, among other things. I'd like to execute some JavaScript after the document has been "loaded" (HTML fully downloaded and in-RAM). Are there any events that I can hook onto when my script executes, that will get triggered on page load?
As Daniel says, you could use document.onload.
The various javascript frameworks hwoever (jQuery, Mootools, etc.) use a custom event 'domready', which I guess must be more effective. If you're developing with javascript, I'd highly recommend exploiting a framework, they massively increase your productivity.
If you are using jQuery,
$(function() {...});
is equivalent to
$(document).ready(function () { })
See What event does JQuery $function() fire on?
look here: http://msdn.microsoft.com/en-us/library/ie/ms536957(v=vs.85).aspx
use self execution onload function
These solutions will work:
or
or even
Note that the last option is a better way to go since it is unobstrusive and is considered more standard.
Reasonably portable, non-framework way of having your script set a function to run at load time: