Javascript using DOMContentLoaded as multiple html files needed

169 Views Asked by At

I have some javascript that runs nicely when added to the end of a HTML file. However, I need the same script on multiple html files so attempting to add it to js file. All the links are fine as I already have other functions added. The documentation recommends using DOMContentLoaded along with a readystate function. It prints the first console.log and 'print loading' from if statement, and then stops. Can someone please help?

function addbutton(){
    let cartbutton = document.getElementsByName('ropebutton');
    console.log(cartbutton) // prints node []
    const cart = [];
    
    for(var i = 0; i < cartbutton.length; i++) {
        let button = cartbutton[i];
        console.log(button);
        button.addEventListener('click', (event) => {
            console.clear();
            console.log(event.target);
            console.log(event.target.dataset.test);
            cart.push(event.target.dataset.test);
            console.log(cart)            
        });
    }
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', addbutton);
    console.log("print loading");
} else {
    addbutton();
    console.log("print loaded");
}
1

There are 1 best solutions below

4
tacoshy On

Simply add the defer attribute to the style tag <script src="URL" defer></script> then you still load the script async'ed but the script will wait to be executed after all DOMContent is loaded.