Buzut
Buzut

Reputation: 5183

Minimum requirements for script tag & page validity

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.

Upvotes: 0

Views: 135

Answers (1)

unor
unor

Reputation: 96737

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.

Upvotes: 2

Related Questions