Script as blocking element and dynamic script loading using document.write
We all know that script is blocking element, meaning no content will be rendered untill script block is parsed and executed or downloaded then parsed and then executed in case of externale script.
And we were told endless times that the best practice is to load scripts at the end of web page. It’s true.
We also have document.ready events thanks to numerous javascript frameworks that gives us opportunity to perform most of our JS actions when document is ready to be manipulated. But there are cases when you do need JS blocking features.
Many ad serving systems work using document.write (One I’m have very good knowledge of is RealMedia), sometimes you need to load different versions of your scripts or your content rendering depends on some script and you have to be sure nothing is loaded untill your script is ready or may be you have script that depends on some script and you are not sure that this framework is loaded. Here comes document.write to your assistance.
I’m sure many people will say that I can load scripts using appendElement and then load depending scripts on it’s load event. This is also true, may be in my next post I will talk about this kind of script loading. But now lets see some samples.
Example #1
<div style="border: 1px solid blue;width:200px;padding:10px;">
Static element content
<script type="text/javascript">
document.write("<script type=\"text\/javascript\"
src=\"writeContent.js\"><\/script>");
</script>
</div>
Content of the writeContent.js file:
document.write("<div style=\"border:1px solid red;width:200px;\">
Dynamic element content<\/div>")
The result is pretty obvious:

In our next example we have some JS in in writeVariable.js file and we want to load and use it:
<div>
<script type="text/javascript">
document.write("<script type=\"text\/javascript\"
src=\"writeVariable.js\"><\/script>");
alert(myVar);
</script>
</div>
Content of the writeContent.js file:
var myVar = "Some value";
You would expect to see alert “Some value” but actually you will get “myVar is undefined” error. Why? Look at the HTML structure created and understand why:
![]()
Script block that you wrote created right after script block that was executed, so obviously at the time you tried to alert myVar it didn’t exist in the document.
The correct way to write it would be:
<div>
<script type="text/javascript">
document.write("<script type=\"text/javascript\"
src=\"writeVariable.js\"><\/script>");
</script>
<script type="text/javascript">
alert(myVar);
</script>
</div>
You need to split your script into two blocks one writing the script and then second one using its data.
A few posts you might find interesting:

Recent Comments