日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

commonJs原理解析

發(fā)布時間:2024/4/17 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 commonJs原理解析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

同步加載

  • 先使用require.register注冊文件路徑和對應方法之間的映射關系保存在require.modules中
  • 再使用require方法,通過傳入的路徑去require.modules中取出對應的方法
  • 使用require獲取方法的同時,會觸發(fā)依賴模塊中的require方法,這樣就實現了模塊的加載
  • 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' })

    異步加載

  • 異步加載的邏輯匜不復雜,在同步加載的基礎上增加require.ensure方法,預先在modules對象上掛在onload方法
  • 修改require.register方法,增加異步模塊注冊邏輯,在異步模塊注冊完成后觸發(fā)onload,以達到模塊異步加載的需求
  • 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原理解析的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。