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.)

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Jed Schmidt
  • 2,907
  • 23
  • 23
  • When you say ALL browsers do you mean the big 3 (Firefox, IE, Safari) or do you mean ALL browsers. – Kredns May 11 '09 at 23:04
  • How about all of those supported by the latest jQuery? From their site: IE 6.0+, FF 2+, Safari 3.0+, Opera 9.0+, Chrome – Jed Schmidt May 11 '09 at 23:07

3 Answers3

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

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

Community
  • 1
  • 1
Jed Schmidt
  • 2,907
  • 23
  • 23
5

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
  • 54,908
  • 28
  • 127
  • 156
1

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

javascript:with(document)(body.appendChild(createElement('script')).src='URL')._
matyr
  • 5,774
  • 28
  • 22