This article helped explain how the browser is pulling in scripts, but what's the best practice to check an object exists before attempting to initialize it?
In linking headroom.js here, I'm currently checking if the window object contains it. Is this okay, or should I be using some form of script.onload ?
<script src="js/main.js"></script>
<script src="js/libs/ScrollTrigger.min.js" defer></script>
<script src="https://unpkg.com/headroom.js@0.9.4/dist/headroom.min.js" async></script>
<script defer>
document.addEventListener('DOMContentLoaded', function(){
// setup ScrollTrigger (animate when item comes into view)
var trigger = new ScrollTrigger({
offset: {x:0, y:300},
once: true
});
// bind Headroom to nav
if(window.Headroom){
init_headroom();
}else{
console.log('polling for Headroom '+Date.now());
let poll_for_headroom = window.setInterval(function(){
if(window.Headroom){
clearInterval(poll_for_headroom);
init_headroom();
}
},20);
}
More questions: 2a) Will this kind of polling block UI? 2b) Should I be checking if "ScrollTrigger.min.js" exists?