14

Using jsdom.jsdom() in express.js I create a document with some 'base' layout markup and attach a few client side libraries such as jQuery to its window.

It would be nice to only have to do this setup once.

The problem is that the DOM of the window's document will change depending on the requested url. Is there a way for each request to start from the same cached window object and enhance it or does it have to be setup from scratch on every request?

cjroebuck
  • 2,273
  • 4
  • 30
  • 46
  • Zombie.js, which uses jsdom internally, has a fork method. It is advertised as a way to solve the same sort of problem as yours, I think, but I don't know how it does it. – Bijou Trouvaille Aug 23 '12 at 05:49

2 Answers2

1

It sounds like you want a simple JavaScript object hash?

var cache = Object.create(null); // avoids spurious entries for `hasOwnProperty` etc.

// Incoming request happens, assume `req.url` is available...

if (req.url in cache) {
    processDom(cache[req.url]);
} else {
    jsdom.env(req.url, function (err, window) {
        if (err) {
            // handle error
            return;
        }
        cache[req.url] = window;
        processDom(cache[req.url]);
    });
}
Domenic
  • 110,262
  • 41
  • 219
  • 271
0

I don't think this is possible. When you create a new document using the jsdom builder, any custom options you specify will only affect the document that is currently being created. Any additional documents created after this point will rely on default features.

However, you can actually modify these default features -- which is what you're after, I think. Before you create any documents, you can modify these defaults for all future documents:

require('jsdom').defaultDocumentFeatures = {
  FetchExternalResources   : ['script'], 
  ProcessExternalResources : false,
  MutationEvents           : false,
  QuerySelector            : false
}

An explanation of each option is available by reading jsdom's README.

hohner
  • 11,498
  • 8
  • 49
  • 84
  • 1
    The question is not about changing the JSDOM features/options. It is about cloning/caching the created window object for reuse. – rkusa Apr 10 '12 at 11:35