Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jsdom window caching

Tags:

dom

express

jsdom

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?

like image 878
cjroebuck Avatar asked Oct 19 '11 23:10

cjroebuck


People also ask

Is JSDOM fast?

JSDOM is a pure javascript implementation of the DOM so it's not even designed to act like a real browser. It's for doing some unit testing. And it's great on doing it, it's fast.

What is Jsdom used for?

JSDOM is a library which parses and interacts with assembled HTML just like a browser. The benefit is that it isn't actually a browser. Instead, it implements web standards like browsers do. You can feed it some HTML, and it will parse that HTML.


1 Answers

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]);
    });
}
like image 94
Domenic Avatar answered Nov 25 '22 05:11

Domenic