Sameer Kochhar

Navigation

Skip navigation.

Search

Site navigation

Email conversation

FromSameer Kochhar
ToMe
Subjectwriting html content in <head> tag during page load
Date11 March 05 01:02
hi,
 
i'm wondering if you have any thoughts on the stability / support /
correctness of using document.write() within a <head></head> section to
write out inline <div> elements during page load.
(i know that writing inside the <body> tag will work fine)
 
eg:
<html><head><script>document.write("<div id='blah'></div>");</script></head>
<body>my page</body></html>
 
i've tested with a few 4th and 5th gen browsers and all seems to work fine.
Lots of google/groups searches have come up with "its not correct, but most
browsers will correctly honour it".
 
hoping you'll have some insight on whether it is safe, unsafe,
and possible reasons why it wouldnt be a good idea to use.
(i know about dynamically generating layers in 5th level browsers, but it
isn't supported in all 4th level ones)
 
oh btw, thanks for putting together an extremely useful site
 
cheers,
sameer
FromMe
ToSameer Kochhar
SubjectRe: writing html content in <head> tag during page load
Date16 March 2005 12:54
Sameer,

> i've tested with a few 4th and 5th gen browsers and all seems to work
>fine.

Indeed. This is because when parsing HTML, browsers use a 'tag soup'
approach, where they assume the page will be invalid, and they will do
their best to interpret what the page author intended.

In this particular case, what you are attempting to do is invalid, as the
end document will have a DIV within the HEAD. Although the page might
validate (assuming the rest of your page is validly written), that is
because the HTML validator only validates the HTML it sees, it does not
validate the resultant document after parsing scripts.

I cannot recommend writing a DIV within the page head for the following
reasons:

1. You are relying very heavily on the browsers' error correction. Each
browser will have a different approach to this as there is no standard for
error handling. Although it may work, there would probably be differences
in resultant DOM. As a result styling or scripting may be unreliable and
not work as you expect in all browsers.

2. It is not future proof. Although it may work now, browser behaviour
regarding errors may change in future, and you would need to rewrite your
page.  Also, if you ever find the need to convert your pages to using
alternative content types, it will fail and again, it would need to be
rewritten.

Hope this helps you make a decision.

Mark 'Tarquin' Wilton-Jones - author of http://www.howtocreate.co.uk/
This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.