Skip to content

Instantly share code, notes, and snippets.

@pardamike
Last active April 18, 2018 17:08
Show Gist options
  • Save pardamike/bdb3cd9e0a5f86fcf8da3d9af03d540d to your computer and use it in GitHub Desktop.
Save pardamike/bdb3cd9e0a5f86fcf8da3d9af03d540d to your computer and use it in GitHub Desktop.
/* If you are able to load your scripts at the END of your body
* (right before the closing </body> tag), you can use a self invoking
* function, which is nothing more than a function that executes
* as soon as the browser reads it.
*/
(function () {
// Code to be immediatly ran goes in here
)();
// Your </body> will be the only HTML that will be after this function, all other HTML must come before it
/* Ok so let's say you have no choice, and your scripts are loaded
* in the <head>, so you need to use some kind document ready.
*/
// Standard jQuery method:
$(document).ready(function() {
// Execute code in here
});
// Shorthand for jQuery $(document).ready():
$(function() {
// Execute code in here
});
// To wait until the ENTIRE page had loaded (images and all) for jQuery:
$(window).on( "load", function () {
// Execute code in here
});
/* So how can we do these with just plain Javascript? Easy! */
// Standard plain Javascript way
document.addEventListener("DOMContentLoaded", function() {
// Execute code in here
});
// The above function will work in IE9 and above. Lets say you need to support IE 8, what then?
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
// Execute code in here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment