0

How to cancel pending script tag request?

I have tag script, who loading content from another server. For some reason server doesn't responce, so i want cancel this pending script by timeout 2sec. For example with img tag I can set src attribute to empty value, and request will be canceled. For script tag this doesn't work. I can't load script content through ajax because CORS restrictions.

  • I'm not sure you can control this via a script tag alone. The solution would be to load the resource via a proxy, e.g. [PHP cURL](http://php.net/manual/en/curl.examples-basic.php), which allows you to set a timeout maximum. – Mitya Oct 28 '16 at 09:59
  • Duplicate: http://stackoverflow.com/questions/2100784/is-it-possible-to-stop-a-dynamically-inserted-script-tag, http://stackoverflow.com/questions/1247611/javascript-cancelling-a-dynamic-script-tag – eithed Oct 28 '16 at 10:01

1 Answers1

0

A script tag cannot be cancelled, because they are loaded and executed synchronously by default. What you can do is use a scriptloader to load the script.

Instead you can do something like this (does not cancel the script though, just makes it so that the page doesn't wait for it):

<script>
    function lazyLoad(s) {
        var d = window.document.body;
        var e = d.createElement("script");

        e.async = true;
        e.src = s;
        b.appendChild(e);
    }

    window.onload = lazyLoad('url to script');
</script>
Robba
  • 7,684
  • 12
  • 48
  • 76