javascript - 終止JS請(qǐng)求的方法有哪些?
問(wèn)題描述
面試時(shí)遇到類(lèi)似問(wèn)題,大意就是,加載頁(yè)面時(shí),會(huì)用script標(biāo)簽加載一些js文件資源,這些資源如果長(zhǎng)時(shí)間沒(méi)有請(qǐng)求回來(lái),怎么手動(dòng)終止請(qǐng)求?
我知道Ajax請(qǐng)求有個(gè)abort方法,不知道面試官是不是想問(wèn)這個(gè),以及還有什么別的請(qǐng)求方式的終止方法嗎?
問(wèn)題解答
回答1:謝邀。像 @小溪流 說(shuō)的一樣,是考察timeout。
大致實(shí)現(xiàn)思路這樣:
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毫秒間隔執(zhí)行隊(duì)列加載,加載時(shí)間在100ms內(nèi)。
回答2:考察的應(yīng)該是加載資源的timeout
回答3:<script>的加載總是同步(阻塞性)的,也不能用DOM操作去影響。題主需要的是獨(dú)立于頁(yè)面加載與渲染的異步JS加載。工具有很多,這里舉一個(gè)RequireJS的例子:
HTML頁(yè)面:
<!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! ');});
相關(guān)文章:
1. golang - 用IDE看docker源碼時(shí)的小問(wèn)題2. nignx - docker內(nèi)nginx 80端口被占用3. javascript - vue使用videojs+videojs-contrib-hls報(bào)錯(cuò)4. io - java 文件操作,如何向指定的位置插入內(nèi)容 (不是替換內(nèi)容) ?5. javascript - JS 里面的 delete object.key 到底刪除了什么?6. javascript - webpack --hot 熱重載無(wú)效的問(wèn)題7. dockerfile - [docker build image失敗- npm install]8. Python 爬蟲(chóng) 遇到的問(wèn)題(手淘問(wèn)大家)9. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””10. mysql如何配置遠(yuǎn)程php外網(wǎng)鏈接數(shù)據(jù)庫(kù)
