To embed or to not embed?

My site has a very small amount of JavaScript. This snippet infact is the entirety of my JavaScript:
(document.getElementById("theme-button").onclick = () => {
const theme = localStorage.getItem("theme") === "light"
? "dark" : "light";
localStorage.setItem("theme", theme);
document
.getElementsByTagName("html")[0]
.setAttribute("data-theme", theme);
})();
(document.getElementById("theme-button").onclick = () => {
const theme = localStorage.getItem("theme") === "light"
? "dark" : "light";
localStorage.setItem("theme", theme);
document
.getElementsByTagName("html")[0]
.setAttribute("data-theme", theme);
})();
Now as a non-webdev, does it make sense performance-wise to embed this in a <script> tag in my HTML? Or can I put this in an external script file that I load in via <script src=…>? I would hope that with browser caching the latter would have zero performance impact after the initial load, but I am not really sure.
31 Replies
ἔρως
ἔρως2mo ago
depends in it's current form, it won't work
Mango Man
Mango Man2mo ago
Why is that?
ἔρως
ἔρως2mo ago
you need to wrap it in a listener for either load or DOMContentLoaded
Mango Man
Mango Man2mo ago
Can I not just put it after the HTML
<html>…</html>
<script>…</script>
<html>…</html>
<script>…</script>
ἔρως
ἔρως2mo ago
basically, just this:
document.addEventListener('DOMContentLoaded', (event) => {
[code comes here]
});
document.addEventListener('DOMContentLoaded', (event) => {
[code comes here]
});
not outside the html, no it will work, by accident, but that's invalid html
Mango Man
Mango Man2mo ago
Is it an accident if the HTML spec is explicit about how to handle misformed input? /s
ἔρως
ἔρως2mo ago
what people also do is to put it at the end of the body
Mango Man
Mango Man2mo ago
Yeah I suppose I can move it there
ἔρως
ἔρως2mo ago
lets just say that people wrote some trully horrible things, and html5 had to "support" it to prevent breaking stuff even further no, put it in the head
Mango Man
Mango Man2mo ago
But this is not really answering my initial question
ἔρως
ἔρως2mo ago
it is in it's current form, you can put it in the html, at the end of the body but it is not the "right way"
Mango Man
Mango Man2mo ago
My question was about using a script tag with JS in my HTML vs using a script tag with src referencing an external file
ἔρως
ἔρως2mo ago
you're focusing on one aspect, im seeing the entire question and in it's current form, there's no answer
Mango Man
Mango Man2mo ago
I don’t really care if it’s the ‘right way’ so long as it works TBH I am just curious about the caching thing
ἔρως
ἔρως2mo ago
if you want an error prone way, just put it at the bottom of the body
Want results from more Discord servers?
Add your server