From 1b3e575a6bcd8b889f2c29278b3a59a212b10aaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Attila=20Ber=C3=A9nyi?= Date: Wed, 18 Jan 2017 17:21:34 +0100 Subject: [PATCH] feat(spriteCache): cache the sprites that are downloaded already --- index.js | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/index.js b/index.js index 27dee71a..5de6c1b8 100644 --- a/index.js +++ b/index.js @@ -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', @@ -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); }