3

js:动态导入script脚本文件

 2 years ago
source link: https://blog.51cto.com/u_13567403/5691600
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

js:动态导入script脚本文件

精选 原创

彭世瑜 2022-09-20 11:07:50 ©著作权

文章标签 html bash 服务器 文章分类 Go语言 编程语言 yyds干货盘点 阅读数170

模仿百度统计的代码,将其封装成一个可重用的函数

<script>
   var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?64ecd82404c51e03dc91cb9e8c025574";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
// 动态导入script
function importScript(src) {
  var hm = document.createElement("script");
  hm.src = src;
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(hm, s);
}

静态服务器

$ pnpm i http-server

# 开启静态服务器
$ npx http-server -p 5500 -c-1
$ tree 
.
├── index.html
├── js
│   └── hello.js
└── script.js

index.html

<!-- 引入js -->
<script src="./script.js"></script>

script.js

// 动态导入script
function importScript(src) {
  var hm = document.createElement("script");
  hm.src = src;
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(hm, s);
}


(function () {
  importScript("/js/hello.js");
})();

js/hello.js

console.log('Hello');
// 导入成功后控制台输出:Hello

访问: http://127.0.0.1:5500/index.html

即可看到控制台输出的内容

  • 打赏
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK