Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proxy injected script shouldn't error when re-evaluated #716

Closed
jackielii opened this issue May 1, 2024 · 0 comments · Fixed by #717
Closed

proxy injected script shouldn't error when re-evaluated #716

jackielii opened this issue May 1, 2024 · 0 comments · Fixed by #717

Comments

@jackielii
Copy link
Contributor

jackielii commented May 1, 2024

Problem

To reproduce this problem, one can setup a basic htmx project. We can use https://github.com/jackielii/templ-live-reload-example/

Once we

  1. clone the project and run make live
  2. open http://localhost:7331/
  3. click the button on the page
  4. hit back browser button

We can see error in the console saying:

Uncaught SyntaxError: Identifier 'templ_reloadSrc' has already been declared (at script.js:1:1)

This is because when we hit back button, htmx restores the html elements from localStorage which includes our injected script tag <script src="/_templ/reload/script.js"></script>. And it gets re-evaluated:

let templ_reloadSrc = new EventSource("/_templ/reload/events");
templ_reloadSrc.onmessage = (event) => {
	if (event && event.data === "reload") {
		window.location.reload();
	}
};

templ_reloadSrc is in global scope, thus the error

Proposed solution

This doesn't cause any trouble, but having the error in the console is not ideal.

I think the fix is to either:

  1. move this to the <head> section
  2. make this script not error when re-evaluated.

I think option 2 is better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant