Generally, to handle my JQuery before or after page loads, will use:
jQuery(function($){
// use jQuery code here with $ formatting
// executes BEFORE page finishes loading
});
jQuery(document).ready(function($){
// use jQuery code here with $ formatting
// executes AFTER page finishes loading
});
ES6 Update
Here's the ES6 version of the script using the arrow function:
// Executes before page finishes loading.
document.addEventListener('DOMContentLoaded', () => {
// Use JavaScript code here.
});
In the first example, we use the DOMContentLoaded
event to execute the code when the HTML document has been completely loaded and parsed.
// Executes after page finishes loading.
window.addEventListener('load', () => {
// Use JavaScript code here.
});
In the second example, we use the load
event to execute the code after all page content has been loaded, including images and other external resources.