您的位置:首页技术文章
文章详情页

javascript - 终止JS请求的方法有哪些?

【字号: 日期:2023-04-28 16:41:48浏览:89作者:猪猪

问题描述

面试时遇到类似问题,大意就是,加载页面时,会用script标签加载一些js文件资源,这些资源如果长时间没有请求回来,怎么手动终止请求?

我知道Ajax请求有个abort方法,不知道面试官是不是想问这个,以及还有什么别的请求方式的终止方法吗?

问题解答

回答1:

谢邀。像 @小溪流 说的一样,是考察timeout。

大致实现思路这样:

var sequence = [’foo’, ’bar’, ’baz’, ’base’, ’ball’, ’hello’, ’world’, ’100k more’], start = Date.now();setTimeout(function _worker() { do { var element = sequence.shift(); // do something with element } while( sequence.length && (Date.now() - start < 100) ); if( sequence.length )setTimeout(_worker, 25);}, 25);

以上例子,25毫秒间隔执行队列加载,加载时间在100ms内。

回答2:

考察的应该是加载资源的timeout

回答3:

<script>的加载总是同步(阻塞性)的,也不能用DOM操作去影响。题主需要的是独立于页面加载与渲染的异步JS加载。工具有很多,这里举一个RequireJS的例子:

HTML页面:

<!DOCTYPE html><html><head><meta charset='utf-8' /><title>Test Page</title><script src='https://cdn.staticfile.org/require.js/2.1.15/require.min.js' data-main='test1'></script></head><body></body></html>

保存为test1.js:

require.config({ paths: {’jquery’: ’//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery’,’underscore’: ’//cdn.bootcss.com/underscore.js/1.7.0/underscore’ },waitSeconds: 20});require([’jquery’], function (module) { console.log('jQuery ' + $.fn.jquery + ' successfully loaded. ');}, function (err) { console.log('SHIT happened while loading jQuery! ');});require([’underscore’], function (module) { console.log(_.last([1, 2, 3, 'Underscore.js successfully loaded. ']));}, function (err) { console.log('SHIT happened while loading Underscore.js! ');});

标签: JavaScript
相关文章: