Adding the script tag before Doctype Declaration

I just did a little test and if I add a script in the manner illustrated below it seems to execute in most modern major browsers. It executes before the page is loaded, I was wondering if this would work across all browsers (including historic)?

<script type="text/javascript">
alert("hello world");

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

I am of course trying to find a way to execute a script to set a page up before any of it is loaded...any input towards this end would be greatly appreciated. Would it be wrong to use this method?

Thanks in advance for any help!



The script gets executed, but the the markup (any element before a DOCTYPE string) puts some browses to quirks mode, which means a large number of poorly documented quirks and oddities, and mess, too.

So whatever your reasons are, you should at least put the element in the first syntactically correct place, namely right after the <head> tag. This can hardly matter as compared with placing it at the start of the document.

Whether the placement solves your real problem is an entirely different thing. You should ask a separate question, clearly describing the problem (rather than an assumed solution), preferably illustrated by some code that demonstrates the problem.


According to the specs,

A conformant document in the HTML syntax must consist of the following parts, in the following order:

  1. Optionally, a single U+FEFF BYTE ORDER MARK (BOM) character.
  2. Any number of comments and space characters.
  3. A doctype.
  4. Any number of comments and space characters.
  5. An html element, with its attributes (if any) and its contents (if any).

Browsers follow these specs, and your code (even though works now) may break in the future, since it clearly breaks the rule of order of elements.

Secondly, it's almost always better to load the scripts last for performance gain.


You mention in the comments that you want to hide/show elements before the page is displayed and that onload is too slow. Try using the DOMContentLoaded instead is it triggers as soon as the HTML DOM is built but before all images CSS and other external references is loaded.

That has always worked for me - though I use jQuery's ready event to make it work cross-browser. And it keeps your HTML valid.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.