Wednesday, February 9, 2011

Sundae.js - script tag injecting

Have you ever wanted to add in a Javascript file to your page? The answer is surprisingly simple. I was faced with this problem in one of my current projects Sundae.js, however the problem requires a little bit of explanation. Sundae is supposed to render canvases and display them on the page for your visual comparison, it also generates a pixel difference based on exact pixel values. So in order to let your test function render to the browser I needed to dynamically load Javascript libraries and Javascript files containing your test functions.

As with most things Javascript, you can do anything including creating a script element in the parent window. Here's how:

  1. Make your script object
  2. Set its onload(), very handy for utilizing callback functions
  3. Set the scripts source
  4. Attach the script to the document
The code I use is available here:

The script tag's type is defaulted to Javascript thanks to HTML5. Lastly you can remove the script tag from the window by calling "removeChild(scriptObj);" if your worried about such things.

You're done now! Global attributes from the included Javascript are now within your current global scope.

No comments:

Post a Comment