JavaScript

The whole page just went blank

There is an issue that beginners JavaScript developers frequently face. You read a few tutorials and learn about document.write(). It is equivalent to echo in PHP, or print in many languages. All it does is print a text on the screen. But then you learn how you can cleverly use it in different parts of your page.

<p>My email address is 
<script>
document.write(emailDecoderFunction("&$^@#*@)!#*$@##@#r$*==")); 
</script>
</p>

When the page renders the user sees :

My email address is email@example.com

This is a common tutorial for getting started with JavaScript. Unfortunately, one of the following thing you will learn about will be about event handlers. Now the cool thing is you can make your JavaScript run when the page is loaded.

function writeLongAwesomeString() {
    document.write("Hey look at me, I know JavaScript!");
}
window.onload = function () {
    writeLongAwesomeString();
};

This looks good. You can guess, when the page is loaded you will see your awesome string on the page. Well the problem is, you only see your string and nothing else. The whole page goes blank. What happened?

This is the pitfalls of using document.write() It writes directly on the DOM. In the first example it works well because the page is still rendering. When the page gets to the script tag, it stops, evaluate the code, write on the DOM if it has to, then continue right where it left off.

When the page is already loaded, document.write() starts from the top of the page. It overwrites the DOM with the new content you gave it. You never need to overwrite the whole page.

The alternative and recommended solution is to write inside the element where the content belongs. Let's take the first example and make space for our email.

<p>My email address is <span id="email-placeholder"></span></p>

Now we created a place holder with an ID that JavaScript can access programmatically. Let's dive into code:

function showEmail() {
    var emailHolder = document.getElementById("email-placeholder");
    emailHolder.innerHTML = "email@example.com";
}
window.onload = function () {
    showEmail();
};

Assigning a value to the innerHTML property directly adds the content to the element in question.

So there you have it, if you have code that turns your whole page blank, chances are you are using document.write() after the page is loaded. Appending content using innerHTML is one of the many alternatives.

Want to know when is the right time to run your code? read more here.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only