script標簽兩個變量參數 - async & defer
<script src="main.js" async></script>
- 普通 - 解析到標簽,立刻pending,并且下載執行
- defer - 解析到標簽,開始異步下載,解析完成之后開始執行
- async - 解析到標簽,開始異步下載,下載完成后立刻執行并阻塞原解析,執行結束后,繼續解析
問題出現:
- 污染作用域=>不利于大型項目的開發以及多人團隊的共建
commonjs規范
nodejs制定
- 優點:
CJS率先在服務實現了從框架層面解決依賴、模塊化的問題- 缺憾
針對的是服務端,對于異步依賴沒有很友好地處理解決
特征:
- 通過module+export對外暴露接口
- 通過require進行其他模塊的調用
main.js
const depModule1 = require('./dependecncyModule1')const depModule2 = require('./dependecncyModule2')let count = 0;const obj = {increase: () => ++count;reset: () => {count = 0;// fn(depModule1);// depModule1, depModule2}}exports.increase = increase;exports.reset = reset;module.export = {increase,reset}
const {increase,reset} = require('main.js');increase();reset();
實際執行處理
(function(thisValue, exports, require, module) {const depModule1 = require('./dependecncyModule1')const depModule2 = require('./dependecncyModule2')// 業務邏輯……}).call(thisValue, exports, require, module);// 部分開源源碼,分別傳入全局、指針、框架作為參數(function(window, _, undefined) {// 業務邏輯……})(window, lodash);// window// 1. 避免全局變化 | 全局作用域轉化為局部的時候,提升效率// 2. 編譯時候優化壓縮 (function(c){c}(window))// lodash// 1. 獨立定制復寫,保障穩定// 2. 防止全局工具的全局污染// undefined// 防止被重寫
AMD規范
通過異步加載 + 允許定制回調函數
經典框架:require.js
define(id, [depModule], callback);require([module], callback);// 例子define('amdModule', [depModule1, depModule2], (depModule1, depModule2) => {let count = 0;const obj = {increase: () => ++count;reset: () => {count = 0;// fn(depModule1);// depModule1, depModule2}}// ....})// 使用require(['amdModule'], amdModule => {amdModule.increase();})
CMD規范 - sea.js
- 優點:按需加載,依賴就近
- 缺憾:依賴打包,加載邏輯存在于每個模塊中,擴大了模塊的體積
define('module', (require, exports, module) => {let $ = require('jquery');let depModule1 = require('./dependencyModule1');// ……})
ESM
引入——import
導出——export
import depModule1 from './dependecncyModule1';import depModule2 from './dependecncyModule2';let count = 0;const obj = {increase: () => ++count;reset: () => {count = 0;// fn(depModule1);// depModule1, depModule2}}export default {increase,reset}// 異步加載import('xxx').then(a => {// ../})
瀏覽器相關
一、認識瀏覽器運行態下的JS
包含:BOM DOM ECMAScript
(function(global, context, undefined) {const _class = ['js', 2, {name: 'vue_base'}, {name: 'vue_promote',index: {}}];global.classArr = _class.map(item => item);const _url = location.href; // 路徑地址相關document.title = 'browser';document.getElementById('app');})(window, this)// 簡述// ECMAScript - 基礎邏輯、數據處理// DOM - 對于瀏覽器視窗內HTML文本的相關操作// BOM - 對瀏覽器本身功能區域做的處理
二、BOM
1. location
location.href => ‘https:// www.course.com/search?class=browser#comments’
.origin => https://www.course.com
.protocol => https
.host => www.course.com
.port => ‘’
.pathname => /search/
.search => ?class=browser
.hash => #comments
location.assign(‘url’) 跳轉到指定path,并替換pathname => path
.replace(‘url’) 效果同上,同時替換瀏覽歷史
.reload()
.toString()
- 面試方向
- location本身api操作
- 路由相關:跳轉、參數、操作 => 場景:history hash
- url處理 —— 正則 or 手寫處理
2. history
history.state => 存儲獲取當前頁面狀態
.replaceState => 替換當前狀態
3. navigator
- 瀏覽器系統信息大集合
navigator.userAgent
面試方向:
- UA讀取系統信息 => 瀏覽器兼容性
- 剪切板、鍵盤
- 系統信息采集 => 數據上報 => 數據采集匯總
4. screen
表示顯示區域 —— 屏幕
-
面試方向 - 判斷區域大小
window視窗判斷:
全局入口處
window.innerHeight
window.innerWidth文本處獲取
document.documentElement.clientHeight
document.documentElement.clientWidth網頁內容size => offsetHeight = clientHeight + 滾動條 + 邊框
document.documentElement.offsetHeight
document.documentElement.offsetWidth定位:
scrollLeft / scrollTop - 距離常規左/上滾動的距離
offsetLeft / offsetTop - 距離常規左/上距離el.getBoundingClientRect()
el.getBoundingClientRect().top
el.getBoundingClientRect().left
el.getBoundingClientRect().bottom
el.getBoundingClientRect().right- 兼容性 - IE會多出2像素
三、事件模型
<div id="app"><p id="dom">Click</p></div>// 冒泡: p => div => body => html => document// 捕獲:document => html => body => div => pel.addEventListener(event, function, useCaption) // useCaption 默認 - false// 追問:// 1. 如何去阻止事件傳播?event.stopPropagation(); // => 無法阻止默認事件的發生,比如:a標簽跳轉// 2. 如何阻止默認事件event.preventDefault();// 3. 相同節點綁定了多個同類事件,如何阻止?event.stopImmediatePropagation();// 面試核心:區分不同阻止// 4. 手寫,實現一個多瀏覽器兼容的事件綁定// attachEvent vs addEventListener// 區別:// a. 傳參 attachEvent對于事件名需要加上’on‘// b. 執行順序 attachEvent - 后綁定先執行;addEventListener - 先綁定先執行// c. 解綁 dettachEvent vs removeEventListener// d. 阻斷 e.cancelBubble = true vs e.stopPropagation()// e. 阻斷默認事件 e.returnValue vs e.preventDefaultclass bindEvent {constructor(element) {this.element = element;}addEventListener = (type, handler) => {if (this.element.addEventListener) {this.element.addEventListener(type, handler, false);} else if (this.element.attachEvent) {const element = this.element;this.element.attachEvent('on' + type, () => {handler.call(element);});} else {this.element['on' + type] = handler;}}removeEventListener = (type, handler) => {if (this.element.removeEventListener) {this.element.removeEventListener(type, handler, false);} else if (this.element.detachEvent) {const element = this.element;this.element.detachEvent('on' + type, () => {handler.call(element);});} else {this.element['on' + type] = null;}}static stopPropagation(e) {if (e.stopPropagation) {e.stopPropagation();} else {e.cancelBubble = true;}}static preventDefault(e) {if (e.preventDefault) {e.preventDefault();} else {e.returnValue = false;}}}// 5. 性能優化 - 事件代理<ul class="list"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li></ul><div class="content"></div>var list = document.querySelector(".list");var li = list.getElementsByTagName("li");var content = document.querySelector(".content");// 硬碰硬for(var n = 0; n < li.length; n++) {li[n].addEventListenr('click', function() {// 點擊邏輯})}// 代理后 - 利用冒泡function onClick(e) {var e = e || window.event;if (e.target.nodeName,toLowerCase() === 'li') {const liList = this.querySelectorAll("li")index = Arrary.prototype.indexOf.call(liList, target);}}list.addEventListener('click', onClick, false)
四、網絡
// 實例化const xhr = new XMLHttpRequest()// 發送// 初始化連接 - open初始化連接不會發起真正的請求xhr.open(method, url, async)// 發送請求// 當請求方法為post時 - body請求體// 當請求方法為get時 - 可以為空// 都需要encodeURIComponent進行轉碼xhr.send(data)// 接受xhr.readyStatus// 0 - 尚未調用open// 1 - 已調用open// 2 - 已調用send// 3 - 已接受請求返回數據// 4 - 已完成請求xhr.onreadystatechange = () => {if (xhr.readyStatus === 4) {if (xhr.status === 200) {// 邏輯}}}// 超時xhr.timeout = 1000;// 超時觸發方法xhr.ontimeout = () => {// trace}// 手寫請求封裝ajax({url: 'reqUrl',method: 'get',async: true,timeout: 30000,data: {payload: 'text'}}).then(res => console.log('成功'),err => console.log('失敗'))function ajax(options) {// 參數讀取const {url,method,async,data,timeout} = options;// 實例化const xhr = new XMLHttpRequest()return new Promise((resolve, reject) => {// 成功xhr.onreadystatechange = () => {if (xhr.readyStatus === 4) {if (xhr.status === 200) {// 邏輯resolve && resolve(xhr.responseText)} else {reject && reject()}}}// 失敗xhr.ontimeout = () => reject && reject('超時')xhr.onerror = () => reject && reject(err)// 傳參處理let _params = []let encodeDataif (data instanceof Object) {for (let key in data) {_params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))}encodeData = _params.join('&')}// methods處理// get類型拼接到urlif (method === 'get') {const index = url.indexOf('?')if (index === -1) {url += '?'} else if (index !== url.length -1) {url += '&'}url += encodeData}// 建立連接xhr.open(method, url, async)if (method === 'get') {xhr.send(null)} else {xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;chartset=UTF-8')xhr.send(encodeData)}})}