专业编程基础技术教程

网站首页 > 基础教程 正文

JavaScript-如何在js代码中引用一个js模块?

ccvgpt 2024-10-17 08:54:44 基础教程 8 ℃

ES6 Modules (Browsers)

浏览器从Safari 10.1、Chrome 61、Firefox 60和Edge 16开始支持直接加载ECMAScript模块(不需要Webpack等工具)。

不需要使用Node.js的扩展名;浏览器完全无视模块/脚本的文件扩展名。

JavaScript-如何在js代码中引用一个js模块?

<script type="module">
  import { hello } from './hello.js'; 
  hello('world');
</script>
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

ES6 Modules (Browsers+Dynamic)

脚本根据需要动态加载其他的js文件。

<script type="module">
  import('hello.js').then(module => {
      module.hello('world');
    });
</script>

ES6 Modules (Node.js)

module.exports = {
   hello: function() {
      return "Hello";
   }
}
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

Fetch

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

Script标签加载

HTML中添加一个带有脚本URL的脚本标签。

脚本甚至可以在不同的服务器上(),<script>标签注入到网页的<head>中,或者插入到关闭的</body>标签之前。

//头部引入
function dynamicallyLoadScript(url) {
    let script = document.createElement("script"); 
    script.src = url;  
    document.head.appendChild(script);  // 添加在头部引入
}
//添加异步回调 callback
function dynamicallyLoadScript(url, callback)
{
    //将脚本标签添加到头部
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    //然后将事件绑定到回调函数上。
    script.onload = callback;
    script.onreadystatechange = callback;    //跨浏览器兼容。
    // 加载
    document.head.appendChild(script)。
}

Tags:

最近发表
标签列表