javascript - 終止JS請求的方法有哪些?
問題描述
面試時遇到類似問題,大意就是,加載頁面時,會用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! ');});
相關文章:
1. 在應用配置文件 app.php 中找不到’route_check_cache’配置項2. html按鍵開關如何提交我想需要的值到數據庫3. HTML 5輸入框只能輸入漢字、字母、數字、標點符號?正則如何寫?4. javascript - 請教如何獲取百度貼吧新增的兩個加密參數5. gvim - 誰有vim里CSS的Indent文件, 能縮進@media里面的6. 跟著課件一模一樣的操作使用tp6,出現了錯誤7. PHP類屬性聲明?8. javascript - JS請求報錯:Unexpected token T in JSON at position 09. objective-c - ios 怎么實現微信聯系列表 最好是swift10. java - 安卓接入微信登錄,onCreate不會執行
