Using Javascript document.write for SEO

March 28, 2008 - Reading time: 4 minutes

Search-engines read a bunch of text on your page that may not be relevant. You can use javascript to write text to a page on the client-side, and that text won’t be processed by the search-engines, thus achieving Search Engine Optimization (SEO).

There are a couple ways to do this… the easiest is using javascript’s document.write:


<script type="text/javascript">
document.write('Hello World');
</script>

This works great for simple little messages, but what if you have a large multi-line text string? What if your text has HTML tags and double quotes in it? Then you’re in for some trouble, because the nice little javascript examples will die on you most ingloriously. PHP to the rescue. Use PHP to replace the spaces (and double-quotes)… you may have to escape your double-quotes in the source text.

Extending that simple little example with some meaty text and some PHP, you end up with something like this:


<?php

$text = ”
<p>
Hello,
big, multi-line
\”stuff\”, watch out!
</p>
“;

$text = preg_replace(“/\s+/”,” “,$text);
$text = preg_replace(‘/\\”/’,”””,$text);

?>

<script type=”text/javascript”>
document.write(‘<?php echo $text; ?>’);
</script>

That solution works (at least, it did before I had to replace all the tags with html entities to make this post). The text gets written at that point in the document once it loads on the client-side. Notice that the regular expressions replace double-quotes with 2 single quotes (tricky, eh?), and any excessive space is replaced. But what if you want something more complicated… what if you don’t like the regular expressions and having to escape your double-quotes? The above method is sorta techie for some, and prone to error. There is another solution: use an Ajax library to pipe HTML directly to a div tag. This solution is more scalable because you can put all the HTML in a separate file, and you don’t have to escape characters.

Download this Javascript library from https://www.prototypejs.org/ and copy the file somewhere in your site’s html directory (here I called it div_updater.js and put it in my js directory). Reference the file in a script tag using the ‘src’ element, then use the Ajax.Updater function to specify 1) the div id where the text should be written and 2) the file to be included.


<div id="target_div"></div>
<script type="text/javascript" src="js/div_updater.js"></script>
<script type="text/javascript">
new Ajax.Updater('target_div', 'include_file.php');
</script>

This solution will write the text to where-ever you have the target_div. Just make sure you use give the div an ‘id’ and that its name is referenced correctly by the Updater function. Using one of these solutions, you can utilize javascript to hide text from the search engines.

-- Everett Griffiths

About

Tech tips, reviews, tutorials, occasional rants.

Seldom updated.