Why is this js file loaded and executed on each page change?

  Kiến thức lập trình

I have two page called first.html and second.html.

The template of the two page is the same except for first and second text. Is an example to understand an issue.

  • first.html:
<!doctype html>

<body hx-boost="true">
    First page!

    <a href="/second.html">Go to second page</a>

    <script src="https://unpkg.com/[email protected]"
        integrity="sha384-Y7hw+L/jvKeWIRRkqWYfPcvVxHzVzn5REgzbawhxAuQGwX1XWe70vji+VSeHOThJ"
        crossorigin="anonymous"></script>

    <script src="/test.js"></script>
</body>

</html>
  • second.html:
<!doctype html>

<body hx-boost="true">
    Second page!

    <a href="/first.html">Go to first page</a>

    <script src="https://unpkg.com/[email protected]"
        integrity="sha384-Y7hw+L/jvKeWIRRkqWYfPcvVxHzVzn5REgzbawhxAuQGwX1XWe70vji+VSeHOThJ"
        crossorigin="anonymous"></script>

    <script src="/test.js"></script>
</body>

</html>
  • test.js:
let players = 0;

If I launch a server and open the browser to http://localhost:3000/first.html and then I click on “Go to second page” link I can see in the console the error:

Uncaught SyntaxError: Identifier 'players' has already been declared (at test.js:1:1)

Why?

I expect it to be loaded and executed just one time!

How can I fix?

1

From the documentation for hx-boost, https://htmx.org/attributes/hx-boost/, it looks like this is loading the second page in dynamically and not doing a full page load.

I would probably move the script tags to a <head> section and so only the <body> is updating and not the shared script.

Understanding issue:

The issue might be related to how HTMX handles content updates and script execution. The script test.js is re-executing with players variable being declared twice within the same scope.

Possible Solutions:

  1. Script logic encapsulation:

    // test.js
    
    (() => {
        let players = 0;
        // other logic
    })();
    

  1. Use of var instead of let:

    // test.js
    var players = 0;
    

8

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT