Skip to content

Commit 6092fcc

Browse files
committed
add caching to js name lookups
1 parent 661ef32 commit 6092fcc

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

app/assets/javascripts/content.js

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -104,15 +104,35 @@ $(document).ready(function () {
104104
// Replace this element's content with the name of the page
105105
var tag = $(this);
106106

107-
// TODO: we should be caching this to reduce duplicate requests on the same page
108-
109-
$.get(
110-
'/api/internal/' + tag.data('klass') + '/' + tag.data('id') + '/name'
111-
).done(function (response) {
112-
tag.find('.name-container').text(response);
113-
}).fail(function() {
114-
tag.find('.name-conainer').text("Unknown " + tag.data('klass'));
115-
});
107+
// Instantiate a cache for all page lookup queries (if not already created)
108+
window.load_page_name_cache ||= {};
109+
var page_name_key = tag.data('klass') + '/' + tag.data('id');
110+
111+
if (page_name_key in window.load_page_name_cache) {
112+
// If we've already made a request for this klass+id, we can just insta-load the
113+
// cached result instead of requesting it again.
114+
tag.find('.name-container').text(window.load_page_name_cache[page_name_key]);
115+
116+
} else {
117+
// If we haven't made a request for this klass+id, look it up and cache it
118+
$.get(
119+
'/api/internal/' + page_name_key + '/name'
120+
).done(function (response) {
121+
tag.find('.name-container').text(response);
122+
window.load_page_name_cache[page_name_key] = response;
123+
124+
// Go ahead and pre-fill all tags on the page for this klass+id, too
125+
$('.js-load-page-name[data-klass=' + tag.data('klass') + '][data-id=' + tag.data('id') + ']')
126+
.find('.name-container')
127+
.text(response);
128+
129+
}).fail(function() {
130+
tag.find('.name-container').text("Unknown " + tag.data('klass'));
131+
});
132+
}
133+
134+
135+
116136
});
117137

118138
});

0 commit comments

Comments
 (0)