views:

293

answers:

3

I'm working on a bookmarklet, and thought I'd throw down a challenge: how to inject an external javascript file from a link in as few characters as possible.

Here's the shortest I was able to come up with:

javascript:(function(d){d.body.appendChild(d.createElement('script')).src='URL'})(document)

That's 88 characters without the URL.

Can the Stack Overflow javascript gurus here do better? I'll be accepting the working answer with the fewest characters, so put on your thinking caps!

(One thing: the bookmarklet must work in all major browsers. This is a clever solution, but doesn't work in all major browsers, because it returns a value.)

+4  A: 

I'm not sure why you're wrapping this in a function enclosure — it seems to work perfectly well without and is almost a dozen characters shorter:

javascript:void(document.body.appendChild(document.createElement('script')).src='URL')

Aside from that, however, your implementation looks pretty minimalist.

Ben Blank
This is why: http://subsimple.com/bookmarklets/rules.asp#ReturnValuesThis approach will return the URL, so it won't work in some browsers.
Jed Schmidt
I see, fixed. Still shorter, though not by as much. :-)
Ben Blank
+5  A: 
javascript:void(with(document)body.appendChild(createElement('script')).src='URL')

79 characters. Credit to Ben Blank for the use of void.

Jed Schmidt
but you're using with, which is frowned on in some circles.
antony.trupe
Well, being that the only scope of this code is a bookmarklet, I don't think the usual reasons to avoid it apply.
Jed Schmidt
Most things are frowned on in some circles. For example, some people frown upon IF, saying that GOTOs were much simpler. They are, of course, completely wrong. :-)
Lucas Jones
Never use with, unless your scope is pretty simple. In this case, it's OK.
EndangeredMassa
A: 

Assuming that String.prototype isn't contaminated, we can save some chars.

javascript:with(document)(body.appendChild(createElement('script')).src='URL')._
matyr
ha, that's clever!
Jed Schmidt