diff --git a/src/util/ajax.js b/src/util/ajax.js index 72e6439837f..f581cfc0c1e 100644 --- a/src/util/ajax.js +++ b/src/util/ajax.js @@ -6,6 +6,7 @@ import {isMapboxHTTPURL, hasCacheDefeatingSku} from './mapbox'; import config from './config'; import assert from 'assert'; import {cacheGet, cachePut} from './tile_request_cache'; +import webpSupported from './webp_supported'; import type {Callback} from '../types/callback'; import type {Cancelable} from '../types/cancelable'; @@ -266,6 +267,13 @@ export const resetImageRequestQueue = () => { resetImageRequestQueue(); export const getImage = function(requestParameters: RequestParameters, callback: Callback): Cancelable { + if (webpSupported.supported) { + if (!requestParameters.headers) { + requestParameters.headers = {}; + } + requestParameters.headers.accept = 'image/webp,*/*'; + } + // limit concurrent image loads to help with raster sources performance on big screens if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) { const queued = { diff --git a/test/unit/util/ajax.test.js b/test/unit/util/ajax.test.js index f7e5e5133a2..c206088ef22 100644 --- a/test/unit/util/ajax.test.js +++ b/test/unit/util/ajax.test.js @@ -8,6 +8,7 @@ import { } from '../../../src/util/ajax'; import window from '../../../src/util/window'; import config from '../../../src/util/config'; +import webpSupported from '../../../src/util/webp_supported'; test('ajax', (t) => { t.beforeEach(callback => { @@ -185,5 +186,28 @@ test('ajax', (t) => { t.end(); }); + t.test('getImage sends accept/webp when supported', (t) => { + resetImageRequestQueue(); + + window.server.respondWith((request) => { + t.ok(request.requestHeaders.accept.includes('image/webp'), 'accepts header contains image/webp'); + request.respond(200, {'Content-Type': 'image/webp'}, ''); + }); + + // mock webp support + webpSupported.supported = true; + + // jsdom doesn't call image onload; fake it https://github.com/jsdom/jsdom/issues/1816 + window.Image = class { + set src(src) { + setTimeout(() => this.onload()); + } + }; + + getImage({url: ''}, () => { t.end(); }); + + window.server.respond(); + }); + t.end(); });