javascript - 如何中止脚本加载

标签 javascript jquery jqxhr

是否可以停止以以下方式加载的 JS 文件的加载,是否有任何事件处理程序?

function makeScript(url){    
    script = document.createElement("script");
    script.src = url;
    //when this line is executed the script will be loaded by the browser
    //is there an event where the below script loading can be stopped based                                                                   
    //on some condition                        
    document.head.appendChild(script); 
}

我不想通过 ajax 调用加载脚本,因为 js 文件没有出现在 Chrome 调试器工具的源选项卡下。有一些可能的解决方案,例如使用 //# sourceURL=dynamicScript.js,但我必须将这一行放在所有 js 文件中。我不想编辑所有的 js 文件。如果更改被本地化到 1 个地方,那很好。

最佳答案

评论后

Suppose there are 2 links, clicking on each link loads the js file using the makeScript().If the user clicks on the first link and quickly clicks on second link, I want to abort the loading of first link's js file. If the loading of js file is not stopped then there may be TypeErrors in the script because when the another link is clicked the first link's variable are deleted which will be used by the loading script.

这是我的想法

您可以维护一个全局变量来保存要加载的脚本。根据此变量,您可以执行 document.head.appendChild(script); 代码行。

示例代码

var scriptFilesConfig; //make this global scope variable

并在点击每个链接时将此 url 分配给全局变量。

假设您点击了第一个链接,那么变量将是

scriptFilesConfig = "firstscript.js";

好的,现在我立即点击了第二个链接,那么你必须将这个 url 分配给变量。所以现在你的对象将是这样的。

scriptFilesConfig = "secondScript.js";

现在,在任何给定点,只有当脚本的 url 与全局变量匹配时,您才会执行 document.head.appendChild(script);

所以你的代码会像

function makeScript(url){    
    script = document.createElement("script");
    script.src = url;
    if( url === scriptFilesConfig){  // append it only if the urls match.   
     document.head.appendChild(script); 
    }
}    

关于javascript - 如何中止脚本加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36565774/

相关文章:

javascript - 如何在文本输入旁边创建两个垂直堆叠的按钮

javascript - 使用 jQuery 插件自动格式化结构化数据(电话、日期)(或失败的 vanilla JavaScript)

jquery - 我如何从数据属性中获取其中一个值

ajax - 如何将ajax请求失败链接到jqXHR状态和错误类型?

javascript - 如何对多个 URL 使用 getjson()

javascript - OPTIONS 405(不允许的方法)无论服务器发送 Access-Control-Allow-Methods :OPTIONS, GET、HEAD、POST

javascript - 悬停时显示下拉菜单 - 不起作用

javascript - 使用javascript删除url参数

jquery - Twitter Bootstrap 下拉菜单在点击时禁用了按钮的原始功能

javascript - 如何为附加元素提供 id?