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.
Follow us on Twitter
Subscribe to RSS Feed
No comments have been left yet. Be the first