Last active
June 9, 2022 07:48
-
-
Save FrankFonts/f9bf34b50f9d04d0da4041c13782ae3a to your computer and use it in GitHub Desktop.
Ways to run .js after page has loaded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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