Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(spriteCache): cache the sprites that are downloaded already #14

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
43 changes: 28 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ var glfun = require('mapbox-gl-style-spec/lib/function');
var mb2css = require('mapbox-to-css-font');
var FontFaceObserver = require('fontfaceobserver');

var spriteCache = {};

var functions = {
interpolated: [
'line-miter-limit',
Expand Down Expand Up @@ -321,25 +323,36 @@ function getStyleFunction(glStyle, source, resolutions, onChange) {
var spriteScale;
if (glStyle.sprite) {
spriteScale = ol.has.DEVICE_PIXEL_RATIO >= 1.5 ? 0.5 : 1;
var xhr = new window.XMLHttpRequest();
var sizeFactor = spriteScale == 0.5 ? '@2x' : '';
var spriteUrl = toSpriteUrl(glStyle.sprite, sizeFactor + '.json');
xhr.open('GET', spriteUrl);
xhr.onload = xhr.onerror = function() {
if (!xhr.responseText) {
throw new Error('Sprites cannot be loaded from ' + spriteUrl);
}
spriteData = JSON.parse(xhr.responseText);
onChange();
};
xhr.send();
var spriteImageUrl = toSpriteUrl(glStyle.sprite, sizeFactor + '.png');
spriteImage = document.createElement('IMG');
spriteImage.onload = function() {
if (!spriteCache[spriteUrl]) {
var xhr = new window.XMLHttpRequest();
xhr.open('GET', spriteUrl);
xhr.onload = xhr.onerror = function() {
if (!xhr.responseText) {
throw new Error('Sprites cannot be loaded from ' + spriteUrl);
}
spriteData = JSON.parse(xhr.responseText);
onChange();
};
xhr.send();
var spriteImageUrl = toSpriteUrl(glStyle.sprite, sizeFactor + '.png');
spriteImage = document.createElement('IMG');
spriteImage.onload = function() {
spriteImageSize = [spriteImage.width, spriteImage.height];
onChange();
};
spriteImage.src = spriteImageUrl;
spriteCache[spriteUrl] = {
spriteData: spriteData,
spriteImage: spriteImage
};
} else {
spriteData = spriteCache[spriteUrl].spriteData;
spriteImage = spriteCache[spriteUrl].spriteImage;
spriteImageSize = [spriteImage.width, spriteImage.height];
onChange();
};
spriteImage.src = spriteImageUrl;
}
} else {
window.setTimeout(onChange, 0);
}
Expand Down