Back to Basics: Calling a JavaScript Function on Page Load

March 6th, 2011 - Posted by Steve Marks to (X)HTML / CSS, Javascript / jQuery, Web Development.

For an experienced developer it is often easy to forget that once upon a time they too struggled with even the easiest of tasks and that not everyone has as much experience as them. The learning curve for developers is a steep one and one that I feel is steepest in the first year or two of building websites and applications. As part of the ‘Back to Basics’ series I aim to put into writing the tasks that I remember getting stuck on or that required research to help other new developers and to ease this learning process.

What I want to talk about today is loading a function written in JavaScript when a page first loads. I have outlined a few simple methods for doing this below that will popup an alert box on the page loading:

Method 1 – Adding an ‘onload’ to the <body> tag

<body onload="alert('Hello World!');">

Method 2 – Using JavaScripts window.onload

<script type="text/javascript">
	window.onload = function() {
		alert("Hello World!");
	}
</script>

Method 3 – Using jQuery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript">
<script type="text/javascript">
	$(document).ready(function() {
		alert("Hello World!");
	});
</script>

By using either of the above 3 methods you will get a popup when the page has finished loading.

This entry was posted on Sunday, March 6th, 2011 at 12:30 pm by +Steve Marks and is filed under (X)HTML / CSS, Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first