Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Address #27 - Dedupe in-flight requests and add 2 minute stylesheet caching #35

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion cq-prolyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ var parsed = false;
var documentElement = document.documentElement;
var styleSheets = document.styleSheets;
var createElement = document.createElement.bind(document);
var CACHE_MAX_AGE = 120000;
var CACHE = {};
var IN_FLIGHT = {};

/**
* @param {function()} callback
Expand Down Expand Up @@ -317,10 +320,22 @@ function preprocessSheet(sheet, callback) {
* success or empty string on failure
*/
function loadExternal(href, callback) {
if (CACHE[href]) {
callback(CACHE[href]);
return;
}
if (IN_FLIGHT[href] && IN_FLIGHT[href].length) {
IN_FLIGHT[href].push(callback);
return;
}
var isDone = false;
var done = function(response) {
if (!isDone) {
callback(response || '');
CACHE[href] = response || '';
setTimeout(function() { delete CACHE[href]; }, CACHE_MAX_AGE);

IN_FLIGHT[href].forEach(function(cb) { cb(CACHE[href]); });
delete IN_FLIGHT[href];
}
isDone = true;
};
Expand All @@ -334,6 +349,7 @@ function loadExternal(href, callback) {
try {
xhr.open('GET', href);
xhr.send();
IN_FLIGHT[href] = [ callback ];
}
catch(e) {
if (window.XDomainRequest) {
Expand All @@ -347,6 +363,7 @@ function loadExternal(href, callback) {
try {
xhr.open('GET', href);
xhr.send();
IN_FLIGHT[href] = [ callback ];
}
catch(e2) {
done();
Expand Down