Fix CSS url 404

Viewed 164

Is it possible to catch CSS background | background-image: url(..); errors (e.g 404) with JavaScript and make corrections?

Only option I can think of right now is to loop over all elements in page, check background and background-image property, if present, try to make corrections. This is undesirable fix as you can probably guess.


I've notices that if I use custom Image src setter, it seems that CSS url does make an Image in background and operate on that but even if I change its src, url('images/example.jpg') still stays the same and points to wrong path.

const {get, set} = Object.getOwnPropertyDescriptor(Image.prototype, 'src');

Object.defineProperty(Image.prototype, 'src', {
  set(value) {
    // this gets called even for CSS url()
    return set.call(this, value);
  },
  get() {
    return get.call(this);
  }
});
1 Answers

Service Workers can be used to intercept all the network calls in the browser.

You have to register the service worker like:

const registerServiceWorker = async () => {
  if ('serviceWorker' in navigator) {
    try {
      const registration = await navigator.serviceWorker.register(
        '/sw-test/sw.js',
        {
          scope: '/sw-test/',
        }
      );
    } catch (error) {
      console.error(`Registration failed with ${error}`);
    }
  }
};

registerServiceWorker();

And have the service worker /sw-test/sw.js look like:

const customFetch = async ({ request }) => {
  try {
    const responseFromNetwork = await fetch(request);
    // ADD FALLBACK HERE
    return responseFromNetwork;
  } catch (error) {
    return new Response('Network error happened', {
      status: 408,
      headers: { 'Content-Type': 'text/plain' },
    });
  }
};

self.addEventListener('fetch', (event) => {
  const response = customFetch({
    request: event.request,
  });
  event.respondWith(response);
});

Related