A team that I am working on has gotten into the habit of using <script>
tags in random places in the body of our HTML pages. For example:
<html> <head></head> <body> <div id="some-div"> <script type="text/javascript">//some javascript here</script> </div> </body> </html>
I had not seen this before. It seems to work in the few browsers that I've tested. But as far as I know, it's not valid to put script tags in places like this.
Am I wrong? How bad is it that we are putting script tags within div tags like this? Are there any browser compatibility issues I should be aware of?
Writing inline JavaScript is one of the many things you learn when you want to tinker with how HTML behaves. However, writing JavaScript straight into your HTML pages is not considered a best practice. In fact, it's considered very 90s by today's coding standards.
Always end with a body tag and make sure every single JavaScript part is within the body tag. You can also have links or scripts inside head tags, but it is not recommended unless you are really certain your JavaScript code is too big to have it inline.
The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.
It's perfectly valid.
You wouldn't want to put great big blocks of code mixed up in the markup there (better to use external scripts), but it can be useful to:
add extra binding information for progressive-enhancement (where that data is difficult to fit into a classname or other approach to hiding extended information in attributes); or
where it's necessary to kick off a scripted enhancement as quickly as possible (rather than waiting for window-load/document-ready). An example of this would be autofocus, which can irritate if fired too late.
You may be thinking of <style>
elements, which aren't allowed in <body>
(although most browsers allow it nonetheless).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With