Wrap your code in $(function(){...}) to ensure the DOM is ready before running. This fires when HTML is parsed but before images finish loading. Without it, selectors may find nothing because elements do not exist yet.
Document Ready
Run code only after the DOM is fully loaded:
// Long form
$(document).ready(function() {
console.log('DOM ready');
});
// Short form
$(function() {
console.log('DOM ready');
});
// ES6 arrow
$(() => {
console.log('DOM ready');
});