Service Workers in Construct 2

  • why construct 2 uses service workers fetch event like this

    self.addEventListener("fetch", event =>
    {
    	/** NOTE (iain)
    	 * This check is to prevent a bug with XMLHttpRequest where if its
    	 * proxied with "FetchEvent.prototype.respondWith" no upload progress
    	 * events are triggered. By returning we allow the default action to
    	 * occur instead. Currently all cross-origin requests fall back to default.
    	 */
    	if (new URL(event.request.url).origin !== location.origin)
    		return;
    		
    	// Check for an update on navigate requests
    	const doUpdateCheck = (event.request.mode === "navigate");
    	
    	const responsePromise = HandleFetch(event, doUpdateCheck);
    
    	if (doUpdateCheck)
    	{
    		// allow the main request to complete, then check for updates
    		event.waitUntil(
    			responsePromise
    			.then(() => UpdateCheck(false))		 // not first check
    		);
    	}
    
    	event.respondWith(responsePromise);
    });
    
    self.addEventListener('fetch', event => {
     if (event.request.mode === 'navigate') {
     // See /web/fundamentals/getting-started/primers/async-functions
     // for an async/await primer.
     event.respondWith(async function() {
     // Optional: Normalize the incoming URL by removing query parameters.
     // Instead of 

    example.com/page [/p] // use example.com/page when reading and writing to the cache. [/p] // For static HTML documents, it's unlikely your query parameters will [/p] // affect the HTML returned. But if you do use query parameters that [/p] // uniquely determine your HTML, modify this code to retain them. [/p] const normalizedUrl = new URL(event.request.url); [/p] normalizedUrl.search = ''; [/p] [/p] // Create promises for both the network response, [/p] // and a copy of the response that can be used in the cache. [/p] const fetchResponseP = fetch(normalizedUrl); [/p] const fetchResponseCloneP = fetchResponseP.then(r => r.clone()); [/p] [/p] // event.waitUntil() ensures that the service worker is kept alive [/p] // long enough to complete the cache update. [/p] event.waitUntil(async function() { [/p] const cache = await caches.open('my-cache-name'); [/p] await cache.put(normalizedUrl, await fetchResponseCloneP); [/p] }()); [/p] [/p] // Prefer the cached response, falling back to the fetch response. [/p] return (await caches.match(normalizedUrl)) || fetchResponseP; [/p] }()); [/p] } [/p] }); [/p] [/p]

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Do you have a specific question? If you are just asking "why didn't you write a completely different function", the answer is "because it works differently".

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)