skip to Main Content

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?

2

Answers


  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.

    Login or Signup to reply.
  2. 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 same block 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;
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search