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. python文檔怎么查看?2. python - pycharm 自動刪除行尾空格3. 安全性測試 - nodejs中如何防mySQL注入4. python - pandas按照列A和列B分組,將列C求平均數,怎樣才能生成一個列A,B,C的dataframe5. python - Pycharm的Debug用不了6. html - eclipse 標簽錯誤7. python 利用subprocess庫調用mplayer時發生錯誤8. 請問PHPstudy中的數據庫如何創建索引9. datetime - Python如何獲取當前時間10. javascript - 有適合開發手機端Html5網頁小游戲的前端框架嗎?
