Skip to content

Instantly share code, notes, and snippets.

@FrankFonts
Last active June 9, 2022 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FrankFonts/f9bf34b50f9d04d0da4041c13782ae3a to your computer and use it in GitHub Desktop.
Save FrankFonts/f9bf34b50f9d04d0da4041c13782ae3a to your computer and use it in GitHub Desktop.
Ways to run .js after page has loaded
// vanilla JS solution
window.onload = function(){
CODE HERE;
};
// vanilla JS solution, equivalent to the code above
window.addEventListener("load", function() {
CODE HERE;
});
// vanilla JS solution
// using the DOMContentLoaded event to code to run when the DOM is fully loaded
// without waiting for stylesheets and images to finish loading
document.addEventListener("DOMContentLoaded", function() {
CODE HERE;
});
// vanilla JS solution
// not recommended, but JavaScript method can be called on page load using HTML <body> tag
<html>
<body onload="loaded();"></body>
<script>
function loaded() {
CODE HERE;
}
</script>
</html>
// jQuery solution
$(document).ready(function(){
CODE HERE;
});
// jQuery solution
// the $(handler) can be called, is equivalent to the code above
$(function() {
CODE HERE;
});
// jQuery solution
// watching for the load event on the window object using $(window).on("load", handler) method
$(window).bind('load', function() {
alert('Page is loaded');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment