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">
<head>
    <meta charset="UTF-8">
    <title>Call JavaScript Function on Page Load</title>
</head>
<body onload="bodyOnLoad();">

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

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

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
$(document).ready(function(){
    addListItem("jquery document ready");
});

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

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

Demo



Download

References

You may also like...