📜 ⬆️ ⬇️

Another JavaScript Script Loader

When developing one site, I needed a script loader, as I would like the download to be called from js code. From ready-made solutions found requirejs and yepnope . Requirejs is modular, which didn't suit my requirements. Yepnope is asynchronous, which means that I would have to wrap the callback functions in each file. There was nothing left but to write something myself. And that's what I got: wakeloader - a modular, synchronous script loader for JavaScript. In this article I will tell about him.

Initialization


In the html code you need to add the following:
<script wake-loader src="/loader.min.js"></script> 

Options


In the wakeloader several boot options, here is a list of them:
 string main-file       (main.js) string main  ,     string update  ,      bool quick  true,   main     DOMContentLoaded, false - onload bool cached     object alias   array queue     

Parameters can be set in two ways:

1. By creating an object with parameters


 <script> wakeloader = { mainFile : "/app/main", main : "main", update : "04.04.2013", quick : true, cached : true, alias : { "http://code.jquery.com/" : "jquery/" }, queue : ["/app/widget","jquery/jquery-2.0.2.min",{ "http://some.serv.er/lib/" : ["sugar","backbone"] }] }; </script> <script wake-loader src="/loader.min.js"></script> 

2. Through the attributes of the script tag


 <script wake-loader data-main-file="/app/main" data-main data-update="04.04.2013" data-cached data-quick data-alias='{ "http://code.jquery.com/" : "jquery/" }' src="/loader.min.js"> ["/app/widget","jquery/jquery-2.0.2.min",{ "http://some.serv.er/lib/" : ["sugar","backbone"] }] </script> 

The queue can be set via the data-queue attribute.

Functions


Wakeloader has only two functions: it require and updateQueue .
')
require downloads the scripts you specify, available in the global namespace.
 require('jquery/jquery-1.10.1.min','/app/lastfm-api'); 

After calling the updateQueue function, the first time the page is refreshed, the queue cache will be updated. The function is available only from the wakeloader object.

How it works


It all works quite simply: it was possible to achieve the synchronization of the require function in only one way - loading scripts via XMLHttpRequest and putting the code inside the tags . , .

: , , .



, cached
true , .



require localStorage , .


requirejs, .



( ). , wakeloader c - 700ms, requirejs - 800ms.

UPD: requirejs, shim:



.

GitHub. .
PS: php-cli , wakeloader'a github'e.

Source: https://habr.com/ru/post/182292/


All Articles