How to Call JavaScript Function on Page Load

This tutorial shows how to call a javascript function on page load using various plain JavaScript functions and using JQuery on document ready.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Call JavaScript Function on Page Load</title>
<body onload="bodyOnLoad();">

    <ul id="container"></ul>

    <script src="jquery.min.js"></script>
    <script src="script.js"></script>

The script.js is located in the same directory as the html page.

// onload event of body element
function bodyOnLoad(){
    addListItem("body onload");

// window.onload
window.onload = function() {
    addListItem("window onload");

// event listener
document.addEventListener('DOMContentLoaded', function() {
    addListItem("event listener DOMContentLoaded");
}, false);

// jquery .ready
    addListItem("jquery document ready");

// equivalent to $(document).ready
    addListItem("short jquery document ready");

function addListItem(text){
    var container = document.getElementById("container");
    var li = document.createElement("li");




You may also like...