Lightweight and practical front-end cmd loader based on requirejs+bluebird,50 line code

Source: Internet
Author: User
Tags git clone

The first is the GitHub address, you can use the git clone command can also be downloaded directly from the git page

Https://github.com/kazetotori/js-requireAsync

After downloading the directory structure is like this

-package.json

-index.js

-node_modules

--bluebird

--jquery

--requirejs

Requireasync function

The Requireasync function is a global function defined in Index.js that accepts an infinite number of string arguments, a module name or a module path that needs to be loaded, and the path cannot contain the. js suffix, which is because itself is loaded by Requirejs, this function returns a promise when Reso Lve, an array is returned, and the array contains all the modules that need to be loaded, and when reject, it throws a Requirejs loading error, which is usually not found in the module-as-module path.

Because it is promise, it allows chained loading

1 requireasync (' jquery ', ' Bootstrap '). Then (function  () {2     window[' jquery ') = Arguments[0]; 3     window[' bootstrap '] = arguments[1]; 4     return requireasync (' bootstrap-table '); 5 }). Then (function  () {6     7 })

Co function

The CO function is the same as the Co module of the TJ Great God, but the node module of the TJ Great God can only be used for Nodejs, not for the browser, here is the CO function with the same effect as the Bluebird.coroutine implementation.

Co function is to be able to cooperate with Generator/yield use, so as to achieve async/await effect, about what is generator, Baidu can find out a lot, I do not repeat.

In a word, in the browser environment, basically support generator. So the above code can be written in the form of CMD code, and then with the ES6 deconstruction, it is absolutely cool crooked

This is the code written in the main function.

1 function* main () {2let     [$, bootstrap] = yield requireasync (' jquery ', ' Bootstrap ');  3     yield requireasync (' bootstrap-table '); 4 }

Why use Requireasync plus Co to load modules

1, cmd loading mode more intuitive, load on demand, need to load jquery load jquery, need to load react load react

2, can control the sequencing of loading. I need to focus on that.

Since not all front-end modules use Requirejs organization code, there is a need for a module like this, such as a dependency on jquery, but without requirejs loading

    

1 ! function ($) {  2     "use strict"; 3 4     $.fn.extend ({  5         function  (color) {  6              Return $ (this). css (' background-color ', color); 7         }  8    })  9 } (JQuery);

Requirejs's writing does not control the order of loading, is not written in front of the first load, he is using the script tag, is asynchronous loading, which led to you if you want to load jquery before loading this module (for example, called Jquery-bgcolor.js), You must use the nested code form. Nesting is very ugly, and it is bound to become more and more deep when dependencies become more dependent and do not use REQUIREJS organizations.

It's also a very bad place for AMD.

1 require ([' jquery '],function($) {2     require ([' Jquery-bgcolor '),  function() {3         4    })5 })

But with Requireasync+co, this code is flattened, and it doesn't matter how much you want to rely on.

1 Co (function* () {2     const [$] = yield requireasync (' jquery '); 3     Yield Requireasync (' jquery-bgcolor '); 4     Yield Requireasync (' jquery-bgcolor-blue '); 5     Yield Requireasync (' jquery-bgcolor-blue-white '); 6 })

Use

can refer to the above GitHub address of how to start, is actually the HTML loaded Requirejs, and set Data-main to Index.js, after the code is written in the main function is OK, of course you can also write a main.js, and then modify the Index.js source code to load the Main.js module.

Principle

Index.js code minus comments only 50 + lines, we take a step-by-step look at

1, the first is to configure a bit requirejs, add a few module path, your module can also be configured here

2, we jump to the back to see two function definitions, this is my habit, put the function definition after the main logic

The first slice function without a doubt, just called the Array.prototype.slice function

The second is the Requireasync function, is actually loaded with Requirejs, and then promise will load the module resolve out

3. Back to our main logic, I first defined a variable co here, but I needed to initialize the variable after loading the bluebird.

First I use Requirejs to load Bluebird and jquery, and initialize the CO function.

Bluebird.coroutine the function into a function that returns promise, but simply returning this function does not execute, I need to execute and return directly to this promise

Then I use the CO to execute a generator, first waiting for the DOM to load, the promise state becomes resolve, and then executes the contents of the main function.

You don't want to use jquery here, you can use it directly.

Window.addeventlistener (' Domcontentready ', function () {resolve ()})

To replace

$ (function () {resolve ()})

This way, you can not load jquery.

4, the last is the main function, no doubt, args for the parameters of jquery

Summarize

Generator/yield is really a good feature, originally I was written async/await version, but can only be used in the latest version of Chorme, so changed to use the generator, essentially the same, will be asynchronous code synchronization, with yield instead of callbacks. Now JS, new features If there is anything to look forward to I think I am still more looking forward to import/export, after all, this is the Orthodox module loading mode. And each module maintains its own scope, which is equal to the default closure. So you have to window.jquery=jquery the output to the window.

Nesting and callbacks are naturally as few as possible.

Lightweight and practical front-end cmd loader based on requirejs+bluebird,50 line code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.