/* globals self,Response */
/**
* delay fetch any images without query string parameter
* @param {Event} event
* @ignore
*/
self.onfetch = function ( event ) {
console.log( 'fetching', event );
var req,
blankImg = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
requestURL = new URL( event.request.url ),
search = requestURL.search,
path = requestURL.pathname;
/* Hijack HTML requests that:
1) do not use a query string parameter (unless in experiment mode)
2) do not include a ':' indicating a non-main namespace
3) are being navigated by /wiki/ or /w/index.php
*/
// FIXME: Currently hardcoded wgScriptUrl since service worker doesn't have access to this at current time.
if (
( !search || search.indexOf( 'image-experiment=true' ) > -1 ) &&
path.indexOf( ':' ) === -1 &&
( path.indexOf( '/wiki/' ) === 0 ||
path.indexOf( '/w/index.php/' ) === 0 ) ) {
console.log( 'intercepted' );
req = fetch( requestURL ).then( function ( response ) {
return response.text().then( function ( body ) {
body = body.replace( /src="(.*\.)(png|jpg|jpeg)"/gi, 'src="' + blankImg + '" data-src="$1$2"' );
body = body.replace( /srcset="(.*)"/gi, 'data-srcset="$1"' );
return new Response( body, {
headers: response.headers
} );
} ) ;
} );
event.respondWith( req );
} else {
console.log( 'rejected' );
}
};