Main Page

write

This code writes a
<script/>
tag to the page, which causes the browser to load the external JavaScript
file as it would normally. Note that the string
“</script>”
is split into two parts (
“</scr”
and
“ipt>”
). This is necessary because anytime the browser sees
</script>
, it assumes that the code block
is complete (even if it occurs inside of a JavaScript string). Suppose the previous example were written
without breaking up the
“</script>”
string:
<html>
<head>
<title>Document Example</title>
<script type=”text/javascript”>
document.write(“<script type=\”text/javascript\” src=\”external.js\”>”
+ “</script>”); //this will cause a problem
</script>
</head>
<body>
</body>
</html>
The browser views this page as:
<html>
<head>
<title>Document Example</title>
<script type=”text/javascript”>
document.write(“<script type=\”text/javascript\” src=\”external.js\”>”
</script>
</script>
</head>
<body>
</body>
</html>
As you can see, forgetting to split up the
“</script>”
string causes major confusion. First, there is a
syntax error inside of the
<script/>
tag because the
document.write()
call is missing its closing
parenthesis. Second, there are two
</script>
tags. This is why you must always break up the
“</script>”
string when writing
<script/>
tags to the page using
document.write()
.
Related closely to
write()
and
writeln()
are the
open()
and
close()
methods. The
open()
method
is used to open an already loaded document for writing; the
close()
method is used to close a docu-
ment opened with
open()
, essentially telling it to render everything that was written to it. This combi-
nation of methods is typically used to write to either a frame or a newly opened window, such as the
following:
Remember that both
write()
and
writeln()
must be called before the page has
been fully loaded in order to insert the content properly. If either method is called
after the page is loaded, it erases the page and displays the content specified.
152
Chapter 5
08_579088 ch05.qxd 3/28/05 11:37 AM Page 152


JavaScript EditorFree JavaScript Editor     Ajax Editor


©