blog's People
blog's Issues
webpack模块切分
webpack怎么实现的模块懒加载
思路
- 编译时,利用import语法作为代码切割点,产出切分为多个文件,多切出来的文件套一层webpackJsonpCallback
- 运行时,利用jsonp的套路将文件加载到浏览器,执行webpackJsonpCallback,将模块合并,然后resolve promise
具体实现
- 首先,将import编译为两部分,第一步负责加载远端chunk,合并模块;第二步负责require模块,拿到导出对象exports
- 整个操作由promise串起来,在require.e时生成promise,将resove存储起来,执行webpackJsonpCallback时resolve
webpackJsonpCallback 主要负责模块合并和resolve promise,以下是精简实现,主模块main.js 动态加载 hello.js
首先是简单的hello.js
hello.js 不需要有运行时代码,因为执行时,必然会有 main 的bundle
window.webpackJsonpCallback(['hello', {
"./src/hello.js":
(function(module, exports, require) {
console.log('i am hello')
exports.hello = 'hello world'
exports.a = '123'
})
}])
main.js的实现
(()=> {
var modules = {}
var cache = {}
var installedChunks = {}
function require(moduleId) {
if(cache[moduleId]) {
return cache[moduleId].exports;
}
var module = cache[moduleId] = {
exports: {}
}
modules[moduleId].call(module.exports, module, module.exports, require);
return module.exports;
}
require.ensure = (chunkId) => {
return new Promise((resolve, reject) => {
installedChunks[chunkId] = [resolve, reject];
var url = 'hello.js';
const script = document.createElement('script');
script.onload = () => {
document.head.removeChild(script);
}
script.src = url;
document.head.appendChild(script)
})
}
window.webpackJsonpCallback = function webpackJsonpCallback(data) {
const [chunkId, moreModules] = data;
for(let moduleId in moreModules) {
modules[moduleId] = moreModules[moduleId];
}
installedChunks[chunkId][0]()
}
require.ensure('hello').then(require.bind(require, './src/hello.js'))
.then(result => {
console.log(result.hello)
})
})()
Promise
const STATUS = {
pending: 'PENDING',
fulfilled: 'FULFILLED',
rejected: 'REJECTED'
}
function resolvePromise(promise2, x, resolve, reject) {
if(promise2 === x) {
throw Error('xxs')
}
if((typeof x === 'object' && x !== null) || typeof x === 'function') {
if(x.then) {
x.then(y => {
resolvePromise(promise2, y, resolve, reject)
}, reject)
}
} else {
resolve(x);
}
}
class Promise {
constructor(executor) {
this.status = STATUS.pending;
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if(this.status === STATUS.pending) {
this.status = STATUS.fulfilled
this.value = value;
this.onFulfilledCallbacks.forEach(fn => fn())
}
};
const reject = (reason) => {
if(this.status === STATUS.pending) {
this.status = STATUS.rejected;
this.reason = reason
this.onRejectedCallbacks.forEach(fn => fn())
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
const promise2 = new Promise((resolve, reject) => {
if(this.status === STATUS.pending) {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
});
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
});
});
}
if(this.status === STATUS.fulfilled) {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
});
}
if(this.status === STATUS.rejected){
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
});
}
})
return promise2;
}
}
const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('fsfs')
}, 1000);
}).then(v=> {
console.log(v)
return 123
}).then(v=> {
console.log('2', v)
return new Promise((resolve) => {
setTimeout(() => {
resolve(3000)
}, 2000);
})
}).then(v => {
console.log(v)
})
// console.log(p);
快速排序
最简版本,未处理细节
const input = [5, 8, 1, 24, 9, 0 , 3, 23, 7, 6]
function qSort(arr, left, right) {
if(left >= right) return
let i = left, j = right;
while(true) {
let pivot = arr[j--];
while(arr[i] < pivot) { i++ }
while(arr[j] > pivot) { j-- }
if(i < j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
}else {
break;
}
}
[arr[i], arr[right]] = [arr[right], arr[i]]
qSort(arr, left, i - 1);
qSort(arr, i+1, right)
}
function sort(arr) {
qSort(arr, 0, arr.length - 1)
}
sort(input)
console.log(input)
并发数限制异步控制
function request(urls, max) {
return new Promise((resolve) => {
let index = 0;
let count = 0;
const result = [];
function next() {
if(index >= urls.length) return;
url = urls[index];
const i = index++;
load(url).then(data => {
result[i] = data;
if(++count >= urls.length) {
resolve(result);
} else {
next();
}
})
}
for(let i = 0; i < max; i++) {
next();
}
})
}
const load = (url) => new Promise((resolve) => {
const ms = 100 * Math.ceil(Math.random()*10)
console.log(`before load ${url} ${ms}`);
setTimeout(() => {
console.log(`after load ${url} ${ms}`);
resolve(url+ms);
}, ms);
})
request(['a', 'b', 'c', 'd', 'e'], 2)
.then(data => {
console.log('done data', data)
})
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.