Skip to content

Commit

Permalink
ensure fetch/ajax image requests accept webp when supported (#8262)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewharvey authored and Ryan Hamley committed Oct 17, 2019
1 parent e18977b commit 19f776d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/util/ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -266,6 +267,13 @@ export const resetImageRequestQueue = () => {
resetImageRequestQueue();

export const getImage = function(requestParameters: RequestParameters, callback: Callback<HTMLImageElement>): 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 = {
Expand Down
24 changes: 24 additions & 0 deletions test/unit/util/ajax.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down Expand Up @@ -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();
});

0 comments on commit 19f776d

Please sign in to comment.