admin管理员组文章数量:1567257
来浏览器上使用原生模块需要在script标签上添加type=module属性
例如:
es.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>ES模块化</div>
<script type=module src="./es.js"></script>
</body>
</html>
es.js
function total (a, b) {
return a * b;
}
import * as math from './math.js';
document.body.innerHTML = `PI = ${math.PI}`;
math.js
const PI = 3.14159;
export { PI as PI };
输出结果:
PI = 3.14159
特点:
1、作为模块加载的脚本不会像普通的 script 脚本一样污染全局作用域。
2、默认 defer,支持 async
3、同一模块执行一次(同一模块指相同的url 包括所带的参数)
4、 CORS 跨域限制 (常规的script标签的重要特点是不受CORS限制),而模块化的是受限的, script 标签type=module加强了这方面的安全策略,浏览器加载不同域的脚本资源时,如果服务器未返回有效的 Allow-Origin
相关 CORS 头,浏览器会禁止加载改脚本。
作者:weixin_34146805
来源:CSDN
原文:https://blog.csdn/weixin_34146805/article/details/88029504
版权声明:本文为博主原创文章,转载请附上博文链接!
版权声明:本文标题:浏览器上使用原生ES模块方案 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1726627118a1078879.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论