javascript - 終止JS請求的方法有哪些?
問題描述
面試時遇到類似問題,大意就是,加載頁面時,會用script標(biāo)簽加載一些js文件資源,這些資源如果長時間沒有請求回來,怎么手動終止請求?
我知道Ajax請求有個abort方法,不知道面試官是不是想問這個,以及還有什么別的請求方式的終止方法嗎?
問題解答
回答1:謝邀。像 @小溪流 說的一樣,是考察timeout。
大致實現(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í)行隊列加載,加載時間在100ms內(nèi)。
回答2:考察的應(yīng)該是加載資源的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! ');});
相關(guān)文章:
1. MySQL客戶端吃掉了SQL注解?2. php自學(xué)從哪里開始?3. mysql - AttributeError: ’module’ object has no attribute ’MatchType’4. 數(shù)據(jù)庫 - MySQL 單表500W+數(shù)據(jù),查詢超時,如何優(yōu)化呢?5. 求大神幫我看看是哪里寫錯了 感謝細(xì)心解答6. python - Django分頁和查詢參數(shù)的問題7. javascript - 圖片能在網(wǎng)站顯示,但控制臺仍舊報錯403 (Forbidden)8. javascript - 百度echarts series數(shù)據(jù)更新問題9. phpstady在win10上運行10. python小白的基礎(chǔ)問題 關(guān)于while循環(huán)的嵌套
