Home > Software design >  Javascript and HTML defer tag not working
Javascript and HTML defer tag not working

Time:08-20

The Javascript function below works perfectly when at the bottom of html file. However, I need it in main.js file. It has been suggested that adding the defer tag to the script tag will enable this but unfortunately not. It prints the first console.log but then stops. Any suggestions?

<script src="/static/main.js" defer></script>
// function to add items to shopping
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); // doesn't print
    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)            
    });
};
<div >
        <img src="static/111.jpg" alt="Rope" >
        <button  data-test="rope111" id="rope111" name="ropebutton" onclick="addcart(this.value);" type="submit">$4,500 buy</button>
        <img src="static/112.jpg" alt="Rope" >
        <button  data-test="rope112" id="rope112" name="ropebutton" type="submit">$3,500 buy</button>
        <img src="static/113.jpg" alt="Rope" >
        <button  data-test="rope113" id="rope113" name="ropebutton" type="button">$1,550 buy</button>
    </div>```

CodePudding user response:

There are two methods to have your code executed after loading the HTML content and to avoid blocking the render of the page. Either reference your script at the end of your <body> tag or in <head> but with defer attribute.

You can try referencing the script at the end of your <body> tag like this:

<bod>
    <div >
        <img src="static/111.jpg" alt="Rope" >
        <button  data-test="rope111" id="rope111" name="ropebutton" onclick="addcart(this.value);" type="submit">$4,500 buy</button>
        <img src="static/112.jpg" alt="Rope" >
        <button  data-test="rope112" id="rope112" name="ropebutton" type="submit">$3,500 buy</button>
        <img src="static/113.jpg" alt="Rope" >
        <button  data-test="rope113" id="rope113" name="ropebutton" type="button">$1,550 buy</button>
    </div>

    <script src="/static/main.js"></script>
</body>

I can't see any issues in your JS code that prevent you from using either methods

CodePudding user response:

Previous poster corrected this. I did as Fadi said and put the following at the end of every html file that needed it:

<script src="/static/main.js" defer></script>

I hadn't realised you can use it multiple times. Thank you Fadi Hania.

  • Related