commonJs原理解析
生活随笔
收集整理的這篇文章主要介紹了
commonJs原理解析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
同步加載
index.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><!-- <script src="./commonJS_async.js"></script> --><script src="./commonJS.js"></script><script src="./modules/hello.js"></script><script src="./modules/name.js"></script><script>var hello = require("hello.js");console.log(hello);console.log(require.modules);// require.ensure('./modules/ajax.js', function (obj) {// console.log(obj);// })</script> </body> </html>commonJS.js
function require(path) {let mod = require.modules[path];mod.exports = {};mod.call(window, require, mod, mod.exports);return mod.exports; }require.modules = {};require.register = function (path, fn) {// 異步加載require.modules[path] = fn; }hello.js、name.js
//hello.js require.register('hello.js', function (require, module, exports) {let name = require('name.js')exports.hello_name = 'hello ' + name;exports.hello_world = 'hello world'; }) //name.js require.register('name.js', function (require, module, exports) {module.exports = 'shimingw' })異步加載
commonJS_async.js
function require(path) {let mod = require.modules[path].method;mod.exports = {};mod.call(window, require, mod, mod.exports);return mod.exports; }require.modules = {};require.register = function (path, fn) {// 異步加載if (require.modules[path] && require.modules[path].status === 'loading') {// 異步加載成功require.modules[path].status = 'loaded'require.modules[path].method = fn;require.modules[path].onload(require(path));} else {require.modules[path] = {moduleName: path, // 模塊Idstatus: 'loaded',onload: null,method: fn};} }require.ensure = function (path, cb) {require.modules[path] = {moduleName: path, // 模塊Idstatus: 'loading',onload: cb,method: null};var head = document.querySelector('head')var script = document.createElement('script');script.async = true;script.src = path;setTimeout(() => {head.appendChild(script);},5000 ); }總結
以上是生活随笔為你收集整理的commonJs原理解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Shiro和SpringBoot简单集成
- 下一篇: LeetCode - 121. 买卖股票