Add timeout for CDN link loading: implement timeout mechanism in Head tag
P粉709307865
P粉709307865 2023-09-11 17:44:04
0
1
533

I'm using a CDN to load some styles. For machines without configured proxy it works fine. But sometimes people may use a proxy to connect to a web page that the CDN cannot resolve, causing the page to take a long time to load or not load at all unless the user forces a refresh.

Is there a way to specify an attribute or something on the HTML to avoid trying to load resources when they cannot be parsed?

P粉709307865
P粉709307865

reply all(1)
P粉270891688

As far as I know, there is no native way to stop loading resources. In fact, the request should automatically timeout if the resource cannot be obtained under normal circumstances.

This approach is a bit tedious and there may be better solutions for your specific problem.

But you can try to remove the link tag from the head, and then insert a script to get the content of the cdn, and then dynamically append the style tag containing the content to the head. Similar to this:

(function() {
  <script>
    const controller = new AbortController();
    const HOW_LONG_TO_WAIT_IN_MS = 5000;
    let loaded = false;

    fetch(URL_FOR_CDN, { signal: controller.signal })
      .then(response => response.text())
      .then(text => {
        document.head.append(`<style>${text}</style>`);
        loaded = true;
      });

      setTimeout(() => {
        if (!loaded) controller.abort();
      }, HOW_LONG_TO_WAIT_IN_MS);
})()
</script>

You need to place this script earlier in the header, which will definitely slow down the page load a bit.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template