javascript - 终止JS请求的方法有哪些?
typecho
typecho 2017-06-28 09:28:55
0
3
1006

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

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

typecho
typecho

Following the voice in heart.

全部回复(3)
我想大声告诉你

谢邀。
像 @小溪流 说的一样,是考察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内。

给我你的怀抱

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

typecho

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

HTML页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<script src="//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! ");
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!