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

ensure fetch/ajax image requests accept webp when supported #8262

Merged
merged 5 commits into from
Oct 17, 2019
Merged
Show file tree
Hide file tree
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
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();
});