不得不说js
真是太自由,太强大了
一段js代码可以转成url,并且赋予script标签,进行加载,加载成功后可以直接读取到js中的内容,还可以使用new Worker()
进行多线程运算
script加载
// 一段js文件
function sleep() {
window.aaa = {
a: 1,
b: 2
}
}
// js转bolb url链接
function scriptToUrl(script) {
return URL.createObjectURL(new Blob([`(${script.toString()})()`]));
}
// 动态创建script
function createScript(url,callback) {
const script = document.createElement("script");
script.src = url;
const header = document.getElementsByTagName("head")[0]
console.log(header);
header.appendChild(script);
script.onload = () => {
callback()
}
}
// 测试
let url=scriptToUrl(sleep)
createScript(url,function(){
console.log(aaa);//{a: 1, b: 2}
})
多线程使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>开启js多线程</title>
</head>
<body>
<button id="button">运行</button>
<script>
document.getElementById('button').onclick = function () {
console.log('点击');
let url = scriptToUrl(sleep);
console.log(url);
newWork(url);
test("我应该被阻塞的");
};
function test(msg) {
console.log(arguments);
console.log(msg);
}
//使用for循环实现阻塞
function sleep(d) {
for (var t = Date.now(); Date.now() - t <= 3000;);
console.log("另一个线程循环结束");
}
function newWork(url) {
return myWorker = new Worker(url);
}
// js转bolb url链接
function scriptToUrl(script) {
return URL.createObjectURL(new Blob([`(${script.toString()})()`]));
}
test(123)
</script>
</body>
</html>