不得不说js真是太自由,太强大了
一段js代码可以转成url,并且赋予script标签,进行加载,加载成功后可以直接读取到js中的内容,还可以使用new Worker()进行多线程运算

script加载

  1. // 一段js文件
  2. function sleep() {
  3. window.aaa = {
  4. a: 1,
  5. b: 2
  6. }
  7. }
  8. // js转bolb url链接
  9. function scriptToUrl(script) {
  10. return URL.createObjectURL(new Blob([`(${script.toString()})()`]));
  11. }
  12. // 动态创建script
  13. function createScript(url,callback) {
  14. const script = document.createElement("script");
  15. script.src = url;
  16. const header = document.getElementsByTagName("head")[0]
  17. console.log(header);
  18. header.appendChild(script);
  19. script.onload = () => {
  20. callback()
  21. }
  22. }
  23. // 测试
  24. let url=scriptToUrl(sleep)
  25. createScript(url,function(){
  26. console.log(aaa);//{a: 1, b: 2}
  27. })

多线程使用

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>开启js多线程</title>
  8. </head>
  9. <body>
  10. <button id="button">运行</button>
  11. <script>
  12. document.getElementById('button').onclick = function () {
  13. console.log('点击');
  14. let url = scriptToUrl(sleep);
  15. console.log(url);
  16. newWork(url);
  17. test("我应该被阻塞的");
  18. };
  19. function test(msg) {
  20. console.log(arguments);
  21. console.log(msg);
  22. }
  23. //使用for循环实现阻塞
  24. function sleep(d) {
  25. for (var t = Date.now(); Date.now() - t <= 3000;);
  26. console.log("另一个线程循环结束");
  27. }
  28. function newWork(url) {
  29. return myWorker = new Worker(url);
  30. }
  31. // js转bolb url链接
  32. function scriptToUrl(script) {
  33. return URL.createObjectURL(new Blob([`(${script.toString()})()`]));
  34. }
  35. test(123)
  36. </script>
  37. </body>
  38. </html>