andyskipper.com

a silicon jeremiad

links for 2008-03-13

  • Filed under:
Wednesday
Mar 12,2008

links for 2008-03-07

  • Filed under:
Thursday
Mar 6,2008

links for 2008-03-01

  • Filed under:
Friday
Feb 29,2008

links for 2008-02-26

  • Filed under: DLC
Monday
Feb 25,2008

links for 2008-02-23

  • Filed under: DLC
Friday
Feb 22,2008

links for 2008-02-18

  • Filed under: DLC
Sunday
Feb 17,2008

links for 2008-02-16

  • Filed under: DLC
Friday
Feb 15,2008
Friday
Feb 15,2008

I’ve just implemented some Google Analytics code, and spotted they have a way of dynamically loading an external JavaScript file that I haven’t seen before. There are two tried and tested ways of doing it, one involving a document.write and a cunningly concatenated string, thus:

document.write('<scr' + 'ipt type="text/javascript" src="http://www.example.com/whatever.js"></scr' + 'ipt>');

From what I understand, this practice mainly exists to add support for several legacy browsers, predominantly Mac-based ones like the old IE5 and Netscape, but it also solves issues with some AntiVirus and Firewall software such as Norton. The code Google are now using is very similar, and looks as though it’s designed to solve the same problem:

document.write(unescape("%3Cscript src='http://www.example.com/whatever.js' type='text/javascript'%3E%3C/script%3E"));

As you can see, the trick is in the obfuscation of the script tag itself by using the ASCII values of the greater-than and less-than symbols that indicate a tag opening and closing, followed by their immediate un-obfuscation (I need a dictionary..).

An important thing to note with both of these techniques is that they’ll only work while the page is loading, as a call to document.write from a button’s onclick event, for example, will cause the page to be cleared and replaced with the content you’re writing; hardly ideal in the middle of an Ajax app. An alternative to writing a string containing the script tag to the page is to use the DOM.

You can dynamically create an element, assign attributes to it (eg. a src attribute to set the location of the JavaScript file to load) and attach it to the current document like so:

var elScript = document.createElement("script");
elScript.src = "http://www.example.com/whatever.js";
document.body.appendChild(elScript);

This method can be called at any time, during or after the page load.

links for 2008-02-15

  • Filed under: DLC
Thursday
Feb 14,2008

links for 2008-02-13

  • Filed under: DLC
Tuesday
Feb 12,2008