admin管理员组

文章数量:1529452

来浏览器上使用原生模块需要在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