JavaScript – Execute Function After Page Loads – The Best Way!

JavaScriptA lot of people will shrug this off and just use jQuery’s $(document).load with jQuery.

Well, sometimes you don’t want to use a whole library and want to use a standard JavaScript solution.

You may be thinking then — okay, I’ll go ahead and use window.onload()

Well, depending on what you are doing…that won’t work! Instead, you’ll want to setup an event listener and attach your function.

<script>
	function hullo() {
		alert('Greetings!');
	}
	if (window.attachEvent) {window.attachEvent('onload', hullo);}
	else if (window.addEventListener) {window.addEventListener('load', hullo, false);}
	else {document.addEventListener('load', hullo, false);}
</script>

Leave a Reply

Your email address will not be published.