Skip to content

Instantly share code, notes, and snippets.

@Weiyuan-Lane
Last active March 16, 2019 03:50
Show Gist options
  • Save Weiyuan-Lane/f3b43fd03ba075762fa95319651a8465 to your computer and use it in GitHub Desktop.
Save Weiyuan-Lane/f3b43fd03ba075762fa95319651a8465 to your computer and use it in GitHub Desktop.
Show how a jquery $(document).ready() can be migrated to DOMContentLoaded()
<html>
<head></head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/x.x.x/jquery.min.js" defer></script>
<script>
function initFunc(){
// Do something here for page initialisation
// For example, loading frontend SPA
}
/* The ready event occurs when the DOM has been loaded - not waiting
* on stylesheets, scripts, images and other assets
*
* jQuery shortcut "$" is undefined, since the "defer" attribute
* above ensures that the jquery script is loaded and executed after
* DOMContentLoaded event is fired
*
*/
$(document).ready(initFunc);
/* DOMContentLoaded does the same as above, but without the
* loaded script dependency
*
* Hence it will invoke initFunc
*/
document.addEventListener('DOMContentLoaded', initFunc)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment