doc.write-less JS badges

Replacing document.write in an embeddable script badge with context-specific DOM additions.

A while ago I hacked together a JS include badge for hexday, it was very late at night, and I just needed something that would work quickly.

So I….

ahheemmm….

cough ….

shuffle feet…

well, see it’s like this.

I used document.write to spit out the DOM I wanted to add.

There I said it, I’m sorry, please don’t be angry.

For me at the time it was the quickest way to allow the user to just paste a script include where they wanted the hexday visuals to appear and do nothing else. No additional HTML they needed to add, just paste a go. It was temporary. It was ugly. And most importantly it slowed down the page render due to the use of document.write and people complained (well Tom and Jim did).

I’ve been a touch busy with “work” work the last few weeks, so it wasn’t until today when whilst waiting for a build I was reading one of John Resig’s recent posts. He details a process for allow script tags to have a source and inline script content- something no browsers seem to support. Now the actual example, I don’t see as being amazingly useful. Just have two script tags, it’s not like anything is going to be “better” it just looks a little more tidy, but it got me thinking.

Using the exact same approach, I could find the parent script tag of a script that is running. This is something that is very important to JavaScript widgets, as you want to be able to add all your dom stuff to the dom at the point where the script tag exists.

<script type="text/javascript" charset="utf-8">

    var el = document.createElement("H4");
    el.innerHTML = "THIS IS CREATED CONTENT";
    el.style.color = "red";
    var scripts = document.getElementsByTagName("script");
    scripts[ scripts.length - 1 ].parentNode.insertBefore(el, scripts[ scripts.length - 1 ].nextSibling);

</script>

Demo Page

Bingo, problem solved. Script tag context specific Dom additions.

Hexday widget updated.

My name is Jon Sykes, and I’ve been document.write free for 4 hours.

First published on jpsykes.com.