A team that I am working on has gotten into the habit of using tags in random places in the body of our HTML pages. For example:
It's certainly legal; I've seen it on a few pages here on Exforsys for example.
Now this is a tutorial site showing the basics of HTML and JavaScript so in that context it's perfectly understandable. However, I wouldn't like to see it in production code for anything more than a simple statement or two. Without seeing what you've replaced by // Some JavaScript code here
I wouldn't like to comment.
There shouldn't be any browser issues with this though.
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.
It's valid, but not a good (or recommended) practice.
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?
There's no problem placing a <script>
under any other elements (but it should be inside <head>
or <body>
). There's also no issue in terms of browser compatibility, however, embedding JS scripts on web pages presents serious disadvantages (how/why they are considered bad):
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).
The oft-stated recommendation that scripts should be kept in the header is to ensure that the script is loaded before it is called. This is only an issue for certain event handlers. For other types of script, it doesn't matter, and for some types (such as document.write), it doesn't make any sense.
A few things:
Doing this slows down your page load considerably as the JavaScript code must execute before any of the rest of the page can render. If you're doing a lot of work in that JavaScript code, your browser could hang. You should try to (whenever possible) load your JavaScript code dynamically and at the end of your page (preferably before the </body>
tag).
Purchase and read High Performance JavaScript. It will change the way you write JavaScript code.