To embed or to not embed?
My site has a very small amount of JavaScript. This snippet infact is the entirety of my JavaScript:
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
depends
in it's current form, it won't work
Why is that?
you need to wrap it in a listener for either
load
or DOMContentLoaded
Can I not just put it after the HTML
basically, just this:
not outside the html, no
it will work, by accident, but that's invalid html
Is it an accident if the HTML spec is explicit about how to handle misformed input? /s
what people also do is to put it at the end of the body
Yeah I suppose I can move it there
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
But this is not really answering my initial question
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"
My question was about using a script tag with JS in my HTML vs using a script tag with src referencing an external file
you're focusing on one aspect, im seeing the entire question
and in it's current form, there's no answer
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
if you want an error prone way, just put it at the bottom of the body
What’s error prone about putting it at the end of the body?
well, you're very few modifications away from breaking the script
There will be no modifications, that is the final javascript
It’s a fully static site with a theme toggle
the html can break it too
How?
a wrote
<a
will be enough
or you forget a <textarea>
there's more, but im playing overwatch and cant think of other examplesI mean that is all already being checked for, so I don’t think that’s an issue I need to worry about
I have scripts to make sure I don’t forget tags lul
Unless I misunderstand you
But anyways, I am really curious about the initial question I posed
with the code you have?
yes
you can either put it at the end of the body, or keep it as a script
you save 1 network request, so
I would hope that with browser caching there won’t be that extra request
Or is that a really bad hope?
in terms of caching, html usually isn't cached, and js files may be cached up to 1 month
depends on the cache, the request for the js file may be supressed
and depends on the html
I suppose I’ll just embed it then
it's the most/least efficient, depending on configurations