简体   繁体   English

如何取消待处理的脚本标签请求?

[英]How to cancel pending script tag request?

How to cancel pending script tag request? 如何取消待处理的script标签请求?

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. 由于某种原因,服务器没有响应,因此我想在2秒内取消该pending脚本。 For example with img tag I can set src attribute to empty value, and request will be canceled. 例如,使用img标签,我可以将src属性设置为空值,并且请求将被取消。 For script tag this doesn't work. 对于脚本标记,这不起作用。 I can't load script content through ajax because CORS restrictions. 由于CORS限制,我无法通过Ajax加载脚本内容。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM