v.tabishev v.tabishev - 1 month ago 21
Javascript Question

How to cancel pending script tag request?

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.

Answer

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>
Comments