0

In some occasions, I have pages without any content but a script that does something (ex. sending data through postMessage then closing itself).

In such cases, is the page valid with just <script>doSomeStuff</script> or does it also require a doctype like so:

<!DOCTYPE html>
<html>
<script>doSomeStuff</script>
</html>

Or does the page need full html declaration like:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script>doSomeStuff</script>
</head>
</html>

One might think it's wiser to include <meta charset="UTF-8"> since otherwise the page could suffer from encoding errors and the script mis – or never – interpreted.

Buzut
  • 4,875
  • 4
  • 47
  • 54

1 Answers1

2

If you want to have a valid HTML document, you have to follow the normal rules. There are no exceptions for documents that rely on JavaScript.

For your case, the minimal HTML5 document would be:

<!DOCTYPE html>
<title>Some title</title>
<script>doSomeStuff</script>

The title element is sometimes optional, but likely not in your case.

The meta-charset element is only required if you don’t specify the character encoding in a different manner.

Community
  • 1
  • 1
unor
  • 92,415
  • 26
  • 211
  • 360
  • Thank you for your answer! Is it valid to open the html tag with the doctype ` ` without closing it at the end? – Buzut Oct 09 '16 at 17:48
  • 1
    @Buzut: The DOCTYPE is not the opening tag for the `html` element. If you want to have the `html` start tag, your document would start with: ` ` . For the `html` element, you can omit only the start tag (``) or only the end tag (``) or both tags (like in my minimal example) -- with [exceptions if comments are involved](https://www.w3.org/TR/2014/REC-html5-20141028/semantics.html#the-html-element). – unor Oct 09 '16 at 19:27