Home Web Front-end JS Tutorial A brief analysis of module definition and module loading of seaJs_Seajs

A brief analysis of module definition and module loading of seaJs_Seajs

May 16, 2016 pm 04:45 PM
module

SeaJS is a module loading framework developed by Yubo that follows the CommonJS specification and can be used to easily and happily load any JavaScript module and CSS module style. SeaJS is very small. The small size lies in the fact that the size after compression and gzip is only 4K, and there are very few interfaces and methods. SeaJS has two cores: module definition and module loading and dependencies. SeaJS is very powerful. SeaJS can load any JavaScript module and CSS module style. SeaJS will ensure that when you use a module, other modules it depends on have been loaded into the script running environment. According to Uncle Yu, SeaJS allows you to enjoy the fun of writing code without having to worry about loading problems. Are you tired of so many js and css references? I counted 39 css and js references on the personal homepage of our company website. The impact can be imagined:

1. Not conducive to maintenance, the front end and back end are the same
2. There are too many http requests. Of course, this can be solved by merging, but if there is no direct merging of the back end, the labor cost will be very high. Even if the back end is merged, maintenance , such a long string must be confusing to the eyes

SeaJS can solve these problems very well.

Module definition define

It is relatively simple to define a module, for example, define a sayHello module and create a sayHello.js document:

Copy the code The code is as follows :

define(function(require,exports,module){
exports.sayHello = function(eleID,text) {
document.getElementById(eleID).innerHTML=text;
};
});

Let’s take a look at the exports parameter first. The exports parameter is used to provide the API of the module to the outside world. That is, other modules can access sayHello through this exports method.

Module loading use

For example, there is an element with the id "out" on our page and we want to output "Hello SeaJS!",
then we can first introduce sea.js
and then use the sayHello module:

Copy code The code is as follows:

seajs.use("sayHello/sayHello",function(say){
say.sayHello("out","Hello SeaJS!");
});

use here is the method of using the module:

The first parameter is the module representation, which is represented by the relative path relative to sea.js. The ".js" suffix after sayHello.js can be omitted. Of course, there are many ways to identify this module. Please check the official instructions for details. :http://seajs.com/docs/zh-cn/module-identifier.html
The first parameter is a callback function. say.sayHello() is to call the exports.sayHello method of the sayHello module. Of course, there is a say parameter in the callback function.

Module dependencies

Module dependencies should actually exist when the module is defined. For example, let's rewrite the above sayHello module. Suppose we already have a general DOM module, such as some methods of obtaining elements, setting styles, etc. For example, for such a DOM module, write DOM.js as follows

Copy code The code is as follows:

define(function(require, exports, module) {
    var DOM = {
        /**
* Get the DOM object through the id attribute of the element, the parameter is a string, or multiple strings
* @id getById
* @method getById
* @param {String} id the id attribute
* @return {HTMLElement | Object} The HTMLElement with the id, or null if none found.
*/
        getById: function() {
            var els = [];
            for (var i = 0; i < arguments.length; i ) {
                var el = arguments[i];
                if (typeof el == "string") {
                    el = document.getElementById(el);
                }
                if (arguments.length == 1) {
                    return el;
                }
                els.push(el);
            }
            return els;
        },
        /**
* get gets the object, you can pass in an object or a string, if the string is passed in, the object is obtained by document.getElementById()
* @id get
* @param {String} el html element
* @return {Object} HTMLElement object.
*/
        get: function(el) {
            if (el & amp; amp; amp; & amp; amp; amp; (el.tagName || el.item)) {
                return el;
            }
            return this.getById(el);
        }
    };
    return DOM;
});

那么sayHello模块可以这样编写,为了不影响原来的demo页面,所以我定一个新的sayHelloA模块,我们可以这样编写sayHelloA.js:
复制代码 代码如下:

define(function(require, exports, module) {
    var DOM = require("DOM/DOM");
    require("sayHelloA/sayHello.css");
    exports.sayHello = function(eleID, text) {
        DOM.get(eleID).innerHTML = text;
    };
});

require 函数就是用来建立模块的依赖关系,比如上面sayHelloA模块,就是依赖于DOM模块,因为用到了DOM模块的get方法。
注意这里的var DOM=require("DOM/DOM"),这句是将应用进来的DOM模块赋值给DOM;require("sayHelloA/sayHello.css")是直接应用sayHello.css css模块或者说文件。这样页面上会引用这个css文件。

最近这几天一直捣腾SeaJS,越捣腾越喜欢,感谢玉伯!感谢SeaJS!当然你可能觉得这么简单的几个实例没必要这么做。确实如果js文件少的小项目感觉不错模块化的优势,但是,更多的在js文件多或着中型以上项目这个模块化的优势就体现出来了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WLAN expansion module has stopped [fix] WLAN expansion module has stopped [fix] Feb 19, 2024 pm 02:18 PM

If there is a problem with the WLAN expansion module on your Windows computer, it may cause you to be disconnected from the Internet. This situation is often frustrating, but fortunately, this article provides some simple suggestions that can help you solve this problem and get your wireless connection working properly again. Fix WLAN Extensibility Module Has Stopped If the WLAN Extensibility Module has stopped working on your Windows computer, follow these suggestions to fix it: Run the Network and Internet Troubleshooter to disable and re-enable wireless network connections Restart the WLAN Autoconfiguration Service Modify Power Options Modify Advanced Power Settings Reinstall Network Adapter Driver Run Some Network Commands Now, let’s look at it in detail

WLAN extensibility module cannot start WLAN extensibility module cannot start Feb 19, 2024 pm 05:09 PM

This article details methods to resolve event ID10000, which indicates that the Wireless LAN expansion module cannot start. This error may appear in the event log of Windows 11/10 PC. The WLAN extensibility module is a component of Windows that allows independent hardware vendors (IHVs) and independent software vendors (ISVs) to provide users with customized wireless network features and functionality. It extends the capabilities of native Windows network components by adding Windows default functionality. The WLAN extensibility module is started as part of initialization when the operating system loads network components. If the Wireless LAN Expansion Module encounters a problem and cannot start, you may see an error message in the event viewer log.

Python commonly used standard libraries and third-party libraries 2-sys module Python commonly used standard libraries and third-party libraries 2-sys module Apr 10, 2023 pm 02:56 PM

1. Introduction to the sys module The os module introduced earlier is mainly for the operating system, while the sys module in this article is mainly for the Python interpreter. The sys module is a module that comes with Python. It is an interface for interacting with the Python interpreter. The sys module provides many functions and variables to deal with different parts of the Python runtime environment. 2. Commonly used methods of the sys module. You can check which methods are included in the sys module through the dir() method: import sys print(dir(sys))1.sys.argv-Get the command line parameters sys.argv is used to implement the command from outside the program. The program is passed parameters and it is able to obtain the command line parameter column

Python programming: Detailed explanation of the key points of using named tuples Python programming: Detailed explanation of the key points of using named tuples Apr 11, 2023 pm 09:22 PM

Preface This article continues to introduce the Python collection module. This time it mainly introduces the named tuples in it, that is, the use of namedtuple. Without further ado, let’s get started – remember to like, follow and forward~ ^_^Creating named tuples The named tuple class namedTuples in the Python collection gives meaning to each position in the tuple and enhances the readability of the code Sexual and descriptive. They can be used anywhere regular tuples are used, and add the ability to access fields by name rather than positional index. It comes from the Python built-in module collections. The general syntax used is: import collections XxNamedT

How does Python's import work? How does Python's import work? May 15, 2023 pm 08:13 PM

Hello, my name is somenzz, you can call me Brother Zheng. Python's import is very intuitive, but even so, sometimes you will find that even though the package is there, we will still encounter ModuleNotFoundError. Obviously the relative path is very correct, but the error ImportError:attemptedrelativeimportwithnoknownparentpackage imports a module in the same directory and a different one. The modules of the directory are completely different. This article helps you easily handle the import by analyzing some problems often encountered when using import. Based on this, you can easily create attributes.

How to use DateTime in Python How to use DateTime in Python Apr 19, 2023 pm 11:55 PM

All data are automatically assigned a "DOB" (Date of Birth) at the beginning. Therefore, it is inevitable to encounter date and time data when processing data at some point. This tutorial will take you through the datetime module in Python and using some peripheral libraries such as pandas and pytz. In Python, anything related to date and time is handled by the datetime module, which further divides the module into 5 different classes. Classes are simply data types that correspond to objects. The following figure summarizes the 5 datetime classes in Python along with commonly used attributes and examples. 3 useful snippets 1. Convert string to datetime format, maybe using datet

Detailed explanation of how Ansible works Detailed explanation of how Ansible works Feb 18, 2024 pm 05:40 PM

The working principle of Ansible can be understood from the above figure: the management end supports three methods of local, ssh, and zeromq to connect to the managed end. The default is to use the ssh-based connection. This part corresponds to the connection module in the above architecture diagram; you can press the application type HostInventory (host list) classification is carried out in other ways. The management node implements corresponding operations through various modules. A single module and batch execution of a single command can be called ad-hoc; the management node can implement a collection of multiple tasks through playbooks. Implement a type of functions, such as installation and deployment of web services, batch backup of database servers, etc. We can simply understand playbooks as, the system passes

Ansible Ad-Hoc (peer-to-peer mode) Ansible Ad-Hoc (peer-to-peer mode) Feb 18, 2024 pm 04:48 PM

Official documentation: https://docs.ansible.com/ansible/latest/command_guide/intro_adhoc.html Introduction Ad-hoc command is a command that is temporarily entered and executed, usually used for testing and debugging. They do not need to be saved permanently. Simply put, ad-hoc is "instant command". Commonly used modules 1. command module (default module) The default module is not as powerful as the shell. Basically, the shell module can support the functions of the command module. 【1】Help ansible-doccommand# It is recommended to use the following ansible-doccomm

See all articles