search

Home  >  Q&A  >  body text

Add timeout for CDN link loading: implement timeout mechanism in Head tag

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粉709307865P粉709307865472 days ago535

reply all(1)I'll reply

  • P粉270891688

    P粉2708916882023-09-12 10:52:22

    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.

    reply
    0
  • Cancelreply