The ridiculous case of adding a script element

September 10th, 2011

Adding a script element to a page should be a no-brainer. Yet, it's ridiculously unreliable in the wild - when you don't have any idea of the surrounding markup.

You know the drill - create a script element, point its src to a URL and add it to the page so that script file can be downloaded in a non-blocking manner.

Creating the script is nice and easy:

var js = document.createElement('script');
js.src = 'myscript.js';

The problem is how to add it to the page.

1. to the head

Probably the most common approach is to append to the head of the document:

document.getElementsByTagName('head')[0].appendChild(js);

You get all head elements (there should be only one) and you add the script there so the result is

<html>
  <head>
    <script>
    ...

But what if there's no head in the document? Remember, we want solid robust code that always works.

Well turns out that most browsers will create the head element even if the tag is not there.

Most, but not all as Steve Souders' browserscope test shows. Exceptions include browsers like Opera 8 but also Android 1.6 and one iPhone 3 - hardly old and negligible.

So head is out.

2. add to the body

This is even shorter:

document.body.appendChild(js);

what if there's no <body> tag? Well my test shows that all tested browsers will create a body element. Even one that has a working appendChild() method. Now, while some of those that don't create head, do create body, I'm still a little uncomfortable that I couldn't find a single browser that doesn't create body. Makes me feel a little worried about the testing and data collecting.

But even if we assume that in all browsers, document.body always exist, there's still a problem. IE7 and the dreaded "Operation aborted" error.

If you modify BODY while loading the page and from a script that is not a direct child of body, but nested in another element, you get Operation aborted and nothing works.

Surprisingly simple page fails miserably:

<html>
  <body>
      <div>
          <script>
          var js = document.createElement('script');
          js.async = true;
          js.src = "http://tools.w3clubs.com/pagr/1.sleep-2.js";
          document.body.appendChild(js);
          </script>
      </div>
  </body>
</html>

See it live in IE7 and be amazed

Now operation aborted may be solved with a defer, but maybe not in IE9.

Another reason not to attempt anything with body is if the script is included in the head. At execution time we have not reached <body> yet, so document.body doesn't exist. Demo.

3. use documentElement

document.documentElement is the html doc itself. Now that's got to exist no matter what.

So you go like

var html = document.documentElement;
html.insertBefore(js, html.firstChild);

And it works!

But what if the firstChild is a comment before the head? This makes something kinda weird:


<html>
  <script>
  <!-- comment -->
  <head>
    ..

Script obviously has no place there, but my test page worked in ie6789, and recent versions of FF, Chrome, Safari, Opera.

But looks like there are other browsers where this comment thing fails as reported(btw, good to read the whole post and all the comments) by Google Analytics folks who say they have received complaints when they used to do that. There might be other cases or browsers I didn't try. So reluctantly, we move on.

4. hook to the first script

Ahaa, if you're running a script, then this script must either be inline <script>bla</script> or external <script src="meh.js">. Either way, there's gotta be at least one script tag! Wo-hoo!

So the final solution is:

var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);

No matter where the first script might be, we glue out new one right above it.

Drawback is that looking for script nodes might be a little more expensive than looking for document.documentElement or document.body or the single match of getElemenetsByTagName('head')

There's still a case when there might not be a script element at all. Ah, impossible, since we're running a script there must be a script element! Well (and thanks to @kangax who pointed this to me while he was reviewing JavaScript Patterns!) here's one example:

<body onload="alert('Look ma, executing script without a script tag!')">

Overall while not completely foolproof, this is as close as you can get to being able to achieve the simple task - add a new script node. Isn't web development just magnificent?

(Funny thing if you use this only to load a script asynchronously: in order to load a script (file), you need a script that refers to a script, possibly itself. JavaScript all around.)

Once again the whole snippet:

var js = document.createElement('script');
js.src = 'myscript.js';
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);

“defer” for IE7′s operation aborted error

September 9th, 2011

IE has this "operation aborted" problem (MSDN article) when you try to change your parent while it's not ready.

This is the example they give that causes this error:

<html>
  <body>
    <div>
      <script>
        document.body.innerHTML+="sample text";
      </script>
    </div>
  </body>
</html>

Turns out you can easily solve it by just adding a defer attribute to the script. This works just fine:

<html>
  <body>
    <div>
      <script defer>
        document.body.innerHTML+="sample text";
      </script>
    </div>
  </body>
</html>

Demo page here

BTW, this operation aborted may bite you if you decide to append a script node to the body, like

var js = document.createElement('script');
js.async = true;
js.src = "http://tools.w3clubs.com/pagr/1.sleep-2.js";
document.body.appendChild(js); 

So it's not a good idea to append to the body like this when you don't control the page you're adding this code to, although document.body seems to be always available even when the page doesn't have a <body> tag

Scripting Photoshop with JavaScript

August 20th, 2011

Did you know you can script common Photoshop tasks with JavaScript? Now you do :)

IDE even

When you install PS it comes with a tool called ExtendScript Toolkit, which is an IDE to write scripts - with debugger, console to try stuff out etc.

To launch I just type "Extend" in Spotlight search. I'm guessing it's got to be somewhere in Program Files\Adobe on Windows too.

Here it is:

Getting started

As you can see on the screenshot, it's easy to get started.

app; // the Photoshop application
app.documents; // collection of open files/documents
app.documents[0]; // the first file
app.documents[0].name; // the first file's filename
app.documents[0].layers.length // how many layers in the doc

Running your script

There's a green "play" button in the IDE, it runs your script.

The directive:

#target photoshop

tells the engine that this is a photoshop script. Apparently you can script other Adobe products too.

If you don't have photoshop open, this directive will open it for you. Then it's all you - open a file, hide a layer, save, close, etc

Also if you save your script file with a .jsx extension, you can put in on the desktop and double-click it. Easy as pie.

And finally, if you put it in the appropriate directory (PSDIR/Presets/Scripts), it will show up in Photoshop menus under File -> Scripts

Docs

A *Yahoo* search will find the docs for you right here:
http://www.adobe.com/devnet/photoshop/scripting.html

There's a scripting guide (nice) and a JavaScript reference (the exact object/method names).

There are also VBScript and AppleScript references in case you insist on writing non-portable scripts :)

Generating code

Getting started with a completely new API can be a little uphill-y walk. For me it was especially so when it comes to saving a file with all the options. Worry not, you can generate code too!

Check the scripting guide where it talks about "The ScriptListener Plug-In". It's a plugin that you already have, you just copy it to to the appropriate directory to activate it and then restart PS.

Then whatever you do in photoshop will generate code in a .log file on your desktop. Then you can go back and cleanup that file (it generates somewhat verbose code) and get the parts you need.

Example - Mojotune chords

So for this "JavaScript is Everywhere" talk I gave this year at OSCON (slides) I came up (with a friend's help) with a sample application that I ported to different environments.

The core of it is m.js (m as in mojo, m as in (data) model). It's a portable piece of JavaScript that knows a lot about guitar chords. I wanted to generate nice PNGs with the data from the chord model. So - Photoshop scripting.

The document template is shown here with three visible layers.

This is the guitar's neck and each dot is where you press. The template has a layer for each dot (each fret on each string), appropriately named:

The task is to get the chord configuration, show the corresponding layers and save the file with the chord name as filename.

So I did this manually (while recording the generated code): show a layer, save the file.

Show/hide layers

The generated code for showing a layer looked like an oddly indented piece of overhead:

/////// GENERATED - DON'T!

// =======================================================
var idShw = charIDToTypeID( "Shw " );
    var desc2 = new ActionDescriptor();
    var idnull = charIDToTypeID( "null" );
        var list1 = new ActionList();
            var ref1 = new ActionReference();
            var idLyr = charIDToTypeID( "Lyr " );
            ref1.putName( idLyr, "11" );
        list1.putReference( ref1 );
    desc2.putList( idnull, list1 );
executeAction( idShw, desc2, DialogModes.NO );

This goes out the door since it can be replaced with:

app.documents[0].layers.getByName('11').visible = true;

(11 means first fret on first string)

Save for web

The generated code for saving a PNG is even worse, but I simply reindented it and shoved in into a function and that was that.

function saveFile(filename) {
    // the following is mostly auto-generated by PS
    var idExpr = charIDToTypeID( "Expr" );
    var desc14 = new ActionDescriptor();

    /// 200 more lines...
}

All the chords

Finally the part that I actually had to write myself.

Directives:

#target photoshop
#include "../../lib/m.js"

Notice how easy it is to include a JS file, in my case the data model m.js?

Singe var pattern:

var data,
    i, c, v,
    layer,
    layers = app.documents[0].layers;

The mojo object comes from m.js. How it works is not very important. The thing is it has a mojo.guitar.getChord() method. You give it a chord name and it returns an array - which fret needs to be pressed on each string.

// mojo.guitar.getChord('Am')
// returns [ignore, 0, 1, 2, 2, 0, x]

All we need to do then is loop though the array and show the layers. Then save the file (e.g. Am.png) and then hide the same layers so they don't interfere the next chord. So this is the end result which generates all the chords m.js knows about:

for (c = 0; c < mojo.prettytones.length; c++) {
    for (v = 0; v < mojo.allchords.length; v++) {
        chord = mojo.prettytones[c].split('/')[0];
        chord += mojo.allchords[v];
        data = mojo.guitar.getChord(chord);
        for (i = 1; i <= 6; i++) {
            layer = "" + i + data[i];
            layers.getByName(layer).visible = true;
        }
        chord = chord.replace('#', '-sharp');
        saveFile('~/stoyan/mojo/chords/images/' + chord + '.png');
        for (i = 1; i <= 6; i++) {
            layer = "" + i + data[i];
            layers.getByName(layer).visible = false;
        }
    }
}

Run it and that's it - a bunch of PNG images are written.

Linkies

  • mojotune.jsx - The final script
  • m.js - the data model ("Check out Guitar George, he knows all the chords" - Dire Straits)
  • images - the generated chord PNGs
  • JS everywhere: slides and code

JavaScript classes

May 5th, 2011

OK, think of it as a religious flamewar to the likes of "tabs vs. spaces for indentation". Looks like this particular war is currently (at JSConf and NodeConf) even more heated than it should be. Classes vs prototypes. For or against classes.

I personally don't care about the "winner". The thing is that classes currently don't exist in JavaScript. No such thing. However looks like they might in the next iterations of the language (see latest post from Brendan Eich). Some people miss classes so much that they start calling other things classes or come up with some approximation. Problem is, because classes don't exist, people often mean different things when they say "class".

Sometimes they mean "constructor functions". Sometimes they mean a regular object literal (singleton-type thing. Heck, "singleton" is also open for interpretations). Sometimes they mean an object or a function defined using Crockford's module pattern.

Sometimes it's some completely different home-grown (or library-provided) thingie called klass for example (in my "JavaScript Patterns" book I have one example for educational/thought-provoking purposes). It has to be klass, or _class or something weird. Because class is a reserved word. Unused, but reserved. And one day may be full of meaning. See the problem?

I avoid saying "class". It just doesn't exist. Imagine two months down the road ECMAScript comes up with classes. And they will most certainly not be the classes you may mean today (e.g. classes won't be another name for constructor functions, I'm sure).

So any written text/blog/documentation you've produced will become incorrect and even worse - misleading and confusing.

To summarize:

  • saying "class" today is confusing and takes extra effort to process (what do you mean? what was that again? it doesn't really exist and is not defined in the language, so an extra translation step is required)
  • saying "class" today will read plain wrong tomorrow, will confuse and misinform

Note:
Heck, even I have this "how to define a JavaScript class" post on my other blog. I wrote it years ago when, coming from PHP, I was curious how stuff works in JavaScript. Well I got it wrong then. But fixed it not too long ago because it was top 1 result in google and Yahoo search for "javascript class" and "javascript classes" and I didn't want to continue contributing to the confusion.

Note 2:
To my regret, I couldn't make it to JSConf (aka the best!) nor NodeConf this year (because all girls and women in my life are born in May and it's impossible to travel) so I may be a little off on the level of flamewarfare, but according to Twitter I'm not.

And the winner is…

April 5th, 2011

In the previous post I announced that one person will win a copy of the Brazilian Portuguese translation of JavaScript Patterns. So here's the winner:

@LouMintzer

He wins a signed copy of "Padrões JavaScript". Waiting for your mailing address, Lou :)

Update: Lou Doesn't speak Portuguese, so he gets an English copy. The second winner is:

@puresight

Update: Monty is not too proud of his Portuguese skills either, so third is

@abozhilov

Asen is an awesome JavaScripter, who actually reviewed the book (thanks a million!) and he already has a copy. Next.

@mexitek

How I picked the winner

By writing some JavaScript in the console, of course.

The winner was to be randomly picked from all those who retweet my tweet or post a comment in the announcement. So I had to collect those.

Twitter

The tweet page says there has been 27 retweets (worded a bit like 28, but looks like it's 27). The page only shows about 15 people though and I need all of them. Given how Twitter doesn't let you search older stuff, I was afraid it was too late. I had to check the API first. I was expecting I can hit a few URLs and get the data I need. Tough luck. All these auth keys, tokens, secrets and stuff got me floored.

Luckily Twitter's UI is also using the APIs. Checking the network traffic I was able to spot the request I need!

The URL is:
http://api.twitter.com/1/statuses/49323240014872576/retweeted_by.json?count=15
I only needed to change the count to something over 27, so I made it 30. Lo and behold I got the data!

The rest of the stuff I did in Safari's Web Inspector console.

Visiting the URL:
http://api.twitter.com/1/statuses/49323240014872576/retweeted_by.json?count=30

We have a JSON array as a document.

>>> var a = document.body.innerHTML
>>> a
"<pre style="word-wrap: break-word; white-space: pre-wrap;">[{"profile_link_color":"0084B4","verified":false,"not....]</pre>"

Safari puts all in a PRE behind the scenes, so this is how we get the data:

>>> var source = $$('pre')[0].innerHTML;
>>> source
"[{"profile_link_color":"0084B4","verified":...]"

eval() it:

>>> source = eval(source)
[Object, Object...]
>>> source.length
27

Sounds right. Now let's move all usernames into a new array using the new ECMA5 forEach fancy-ness:

>>> var all = [];
>>> source.forEach(function(e){all.push(e.screen_name)})
>>> all.length
27
>>> all
["jrfaqcom", "gustavobarbosa", "gabrielsilva", ...."vishalkrsingh"]

Blog comments

I had 4 comments on the original post. WordPress puts all comments in a div with class commentlist, so this allows us to grab all comments:

>>> var comments = $$('.commentlist cite a')
>>> comments.length
4

Now let's only grab the names, they are in the href's innerHTML:

>>> var all = [];
>>> comments[0].innerHTML
"Fabiano Nunes"
>>> comments.forEach(function(e){all.push(e.innerHTML)})
TypeError: Result of expression 'comments.forEach' [undefined] is not a function.

Eh? What? Oh, the list of HREFs is not an array but a NodeList:

>>> comments
[
<a href="http://fabiano.nunes.me" rel="external nofollow" class="url">Fabiano Nunes</a>
,
<a href="http://www.gabrielizaias.com" rel="external nofollow" class="url">Gabriel Izaias</a>
,
<a href="http://www.jrfaq.com.br" rel="external nofollow" class="url">João Rodrigues</a>
,
<a href="http://www.jrfaq.com.br" rel="external nofollow" class="url">João Rodrigues</a>
]
>>> comments.forEach
undefined

So, list of nodes converted to array:

>>> comments = Array.prototype.slice.call(comments)

Now forEach is usable:

>>> comments.forEach
function forEach() {
    [native code]
}
>>> comments.forEach(function(e){all.push(e.innerHTML)})

So we have a list of all names. Lets serialize it, so it can be pasted to the other window where we had the Twitter data.

>>> all
["Fabiano Nunes", "Gabriel Izaias", "João Rodrigues", "João Rodrigues"]
>>> JSON.stringify(all)
"["Fabiano Nunes","Gabriel Izaias","João Rodrigues","João Rodrigues"]"

(Simple array join and then string split will do too in this simple example)

All together

Back to the twitter window. Deserializing the comments array:

>>> comments = JSON.parse('["Fabiano Nunes","Gabriel Izaias","João Rodrigues","João Rodrigues"]')
["Fabiano Nunes", "Gabriel Izaias", "João Rodrigues", "João Rodrigues"]

Merging the two arrays

>>> all = all.concat(comments);
["jrfaqcom", "gustavobarbosa", ...."João Rodrigues"]
>>> all.length
31

Perfect. 31 entries. Just as many as the days in March when I announced it. So let's take the 19th array element to be the winner.

But shuffle the array a bit first.

Suffle

Sorting the array by randomness. (I shuffled and reshuffled it three times, just because.)

>> all.sort(function() {return 0 - (Math.round(Math.random()))})
["ravidsrk", "anagami", "lpetrov", ...]

And the winner is:

>>> all[18]
"LouMintzer"

“JavaScript Patterns” now in Brazilian Portuguese

March 20th, 2011

Padrões JavaScript

I've been terrible at promoting this book. But that should change starting today :)

So today I got a copy of "Padrões JavaScript" - the Brazilian Portuguese translation of JavaScript Patterns. Happy, happy, happy!

Given that I already got two copies few weeks ago, kept one and sent one to my mom for her collection, I thought I should give this one away.

If you want to enter for a chance to win a signed copy of the Brazilian Portuguese translation of JavaScript Patterns, you can do one or more of the following:

  • Leave a comment below, or/and
  • Retweet this

That's it, shipping's on me. Boa sorte!

pssst, here are two PDFs: table of contents and about half of chapter 1 for you evaluation pleasure :)

Book is almost out

September 4th, 2010

The JavaScript Patterns book is to be sent to the printer next week and will be available as expected (and mentioned on Amazon) on or before Sept 28. Yey!

Dunno who said: writers don't like to write, they like to have written. Exactly how I feel today.

And let me share a quote from my favorite Kurt Vonnegut along the same lines. The book is Bluebeard.

    She asked me what had been the most pleasing thing about my professional life when I was a full-time painter -- having my first one-man show, getting a lot of money for a picture, the comradeship with fellow painters, being praised by a critic, or what?
    "We used to talk a lot about that in the old days," I said. "There was general agreement that if we were put into individual capsules with our art materials, and fired out into different parts of outer space, we would still have everything we loved about painting, which was the opportunity to lay on paint."
    I asked her in turn what the high point was for writers -- getting great reviews, or a terrific advance, or selling a book to the movies, or seeing somebody reading your book, or what? She said that she, too, could find happiness in a capsule in outer space, provided that she had a finished, proofread manuscript by her in there, along with somebody from her publishing house.
    "I don't understand," I said.
    "The orgastic moment for me is when I hand a manuscript to my publisher and say, 'Here! I'm all through with it. I never want to see it again,' " she said.

So - whew!

Expect a more detailed post about the book (and the wonderful team of JS guru tech reviewers!), after all I have to start promoting it, don't I?

Singleton without a closure

July 17th, 2010

Warning: anti-pattern ahead.

Mwahaha, I feel like a ninja. I mean a ninja by Doug Crockford's definition which means someone who finds a mistake in the language's design, decides it's cool and abuses it.

So there you go. Regular expression objects are created only once if you're using a literal. Such an object can be used to store the single instance of a Singleton() constructor.

Implementation

function Single() {
    "strict me not!";

    var re = / /;
    if (re.instance) {
        return re.instance;
    }
    re.instance = this;
    this.name = "Foo";

}

Single.prototype.getName = function () {
    return this.name;
};

Test

var s1 = new Single(),
    s2 = new Single();

console.log(s1 === s2); // true
console.log(s1.getName()); // "Foo"
s1.name = "dude";
console.log(s2.getName()); // "dude"

Pros

  • The prototype chain works fine
  • No closures
  • No public properties or globals to store the single instance

Cons

  • It's a hack
  • ES5 defines that reg exp literals should no longer work like this

Verdict

Don't use. Please :)

Constants

April 10th, 2010

Although there actually are constants in some environments, e.g. in Firefox you can use const instead of var, in general in JavaScript there are no constants.

Workaround

To work around that limitation, people often use ALLCAPPS to denote "hey, don't touch this var, it's meant to be a constant". It's constant-by-convention but the values can be changed by careless programmer on a bad day. If you really want to protect the value, you need to make it private.

PHP-inspired API

In PHP there are the functions define(name, value) to gefine a constant, defined(name) to check if a constant is defined and constant(name) to get the value of a constants when it's name is assembled at runtime and you don't know it a priori. So I thought - well, we can do the same in JavaScript. Only, let's not use global functions, but a constant global var and make the functions method of that global. constant.constant(name) is a little mouthful, so let's make that one constant.get(name)

Implementation

Here's the simple implementation:

"use strict";

var constant = (function () {
    var constants = {},
        ownProp = Object.prototype.hasOwnProperty,
        allowed = {
            string: 1,
            number: 1,
            boolean: 1
        };
    return {
        define: function (name, value) {
            if (this.defined(name)) {
                return false;
            }
            if (!ownProp.call(allowed, typeof value)) {
                return false;
            }
            constants[name] = value;
            return true;
        },
        defined: function (name) {
            return ownProp.call(constants, name);
        },
        get: function (name) {
            if (this.defined(name)) {
                return constants[name];
            }
            return null;
        }
    };
}());

This is it. Basically protect an object in a closure and don't provide means to change it, but only to add properties to it.

UPDATE: thanks to the comments (see below), there's extra care to check for own properties of the constants private object. This allows to define constants with weird names such as toString and hasOwnProperty. Also only primitive values are allowed to be constants.

Usage

// check if defined
constant.defined("bazinga"); // false

// define
constant.define("bazinga", "Bazinga!"); // true

// check again
constant.defined("bazinga"); // true

// attempt to redefine
constant.define("bazinga", "Bazinga2"); // false

// was it constant or it changed?
// get da, get da, get da value
constant.get("bazinga"); // "Bazinga!"

arguments considered harmful

February 16th, 2010

Inside every JavaScript function an arguments object is available containing all the parameters passed to the function.

function aha(a, b) {
  console.log(arguments[0] === a); // true
  console.log(arguments[1] === b); // true
}

aha(1, 2);

However, it's not a good idea to use arguments for the reasons of :

  • performance
  • security

The arguments object is not automatically created every time the function is called, the JavaScript engine will only create it on-demand, if it's used. And that creation is not free in terms of performance. The difference between using arguments vs. not using it could be anywhere between 1.5 times to 4 times slower, depending on the browser (more info and bench)

As for the security, there is the POLA (Principle of Least Authority) which is violated when one function A passes arguments to another B. Then a number of bad things can happen including:

  • B calls A through arguments.callee - something A never intended when calling B in the first place
  • B overwrites some arguments and causes A to misbehave

While in these scenarios B looks a little malicious, it can actually cause trouble unvoluntarilly. Consider this example that illustrates the second case (B changing values behind A's unsuspecting back)

function A(obj, ar) {

  console.log(obj); // {p: 1}
  console.log(ar);  // [1, 2, 3]

  B(arguments);

  // oops!
  console.log(obj); // {p: 2}
  console.log(ar);  // [1, 2]
}

function B(args) {

  // convenient innocent-looking local vars
  var o=args[0],
      a=args[1];

  // do something with the local variables
  o.p = 2;
  a.pop();

  // now the original arguments is 
  // messed up because objects/arrays
  // are passed by reference
}

A({p: 1}, [1, 2, 3]);

ECMAScript 5

In ECMAScript's "strict mode", using arguments.callee will throw a syntax error.

Recursive anonymous function

Probably the biggest argument for keeping arguments and arguments.callee is so that recursive anonymous functions can be created, because by using the callee property a function can call itself without knowing its own name. Now, this is not such a common scenario, but even if so, you can wrap a named function inside of an anonymous function and voila! - call that named function recursively without leaking a variable to the global scope.