Skip to content
This repository has been archived by the owner on Dec 20, 2022. It is now read-only.

Commit

Permalink
Merge pull request #18 from CapMousse/dev
Browse files Browse the repository at this point in the history
Version 3.0.1
  • Loading branch information
CapMousse authored Sep 9, 2016
2 parents 20380ce + 1d86ad4 commit 2c984c4
Show file tree
Hide file tree
Showing 5 changed files with 112 additions and 62 deletions.
79 changes: 43 additions & 36 deletions README.markdown
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Include.js [![Build Status](https://travis-ci.org/CapMousse/include.js.svg?branch=master)](https://travis-ci.org/CapMousse/include.js)

**Include.js** is a tiny (1,2ko minified and gziped) Javascript loader. It can load normal javascript files or css but is more efficient with **web modules**.
**Include.js** is a tiny (1,3ko minified and gziped) Javascript loader. It can load normal javascript files or css but is more efficient with **web modules**.

When it's possible, it will use async loading to speed up you page and will ensure the good executions of your script. It support **nested dependencies**, a useful feature to create clean and flexible javascript application.

Expand All @@ -12,70 +12,77 @@ Include.js was tested on :
- Safari √
- IE (> 6) √

## How to use
## Define modules

To create a module, create a new javascript file and use `include()` as a wrapper :
In the old javascript days, to create a module, you would add a simple wrapper on your code, like a auto-called anonymous functiom.

```javascript
include(function(){
return {
name : "Mars Curiosity"
}
})
(function(env){
//your code here
})(window);
```

You can name your module with the first argument of `include()`. Name are like `PHP` namespace : `Dir/FileName.js` -> `Dir.FileName`
Now, to define a module meeting the [AMD standard](http://requirejs.org/docs/whyamd.<html id="definition"></html>), just use `include()` as the wrapper of your code.

With AMD definition, you can create module having dependencies realy easily, executing code only when the dependencies are available.

```javascript
include('App.Planet', function(){
return {
name : "Mars",
gravity : 0.376,
saletties : 2
}
})
//define a new module with include
include(['dep1', 'dep2'], function (dep1, dep2) {

//define the module value with return
return dep2({
name: dep1('Mars Curiosity')
});
});
```

Modules can have dependencies to work, as an array on second argument off `include()` :
## Named modules

Modules without a name are automatically named with their file name. This is what makes modules very portable and easily usable in others projetcs.

Naming module manually must be avoided to prevent conflicts or loading missing module. Only use module naming in controlled cases or for better performances.

```javascript
include('App.Nasa', ['App/Rover.js', 'App.Planet'], function(Rover, Planet){
return {
rover : Rover.name,
planet : Planet.name,
success : true
}
//define a named module with dependencies
include('name', ['dep1', 'dep2'], function (dep1, dep2) {
return dep2({
name: dep1('Mars Curiosity')
});
});
```

Modules can also be loaded from other url, and named :
## External dependencies

You can also load external dependencies, useful to speed up website loading time and prevent parsing to be blocked.

External dependencies can be AMD module or normal javascripts. If no module is found, argument send to the callback will be the index of the script in the dependencies array instead of the module function.

```javascript
include('App.Nasa', [['Rover', 'http://your/url/here/script/rover/'], 'App.Planet'], function(Rover, Planet){
return {
rover : Rover.name,
planet : Planet.name,
success : true
}
include(['//website/jquery.js', '//website/amd-module.js'], function (indexOfJquery, amdModule) {
$('#block').text(amdModule());
});
```

And you can load CSS
## Load CSS

You can also load css like any other module. The callback will be called when the browser will have parsed the style.

```javascript
include('path/to/css.css', function(){
//do something when style is apply
})
include(['/styles/alternative.css', '//website/external-css.js'], function (css1, css2) {
//css1 and css2 will be null
});
```


## Already using a script loader ?

If you already use a script loader you can replace it with **Include.js** without problemes and without rewriting code. `define()` and `require()` are supported by **Include.js**. Let's be light !
If you already use a script loader you can replace it with Include.js without problemes and without rewriting code. `define()` and `require()` are supported by Include.js. Let's be light !


## Developed by

- Jérémy Barbe
- [email protected]
- [jeremy.sh](http://jeremy.sh)
- [@capitainemousse](https://twitter.com/capitainemousse)

Expand Down
2 changes: 1 addition & 1 deletion include-min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

55 changes: 42 additions & 13 deletions include.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
(function (environment) {

/**
* List a existings modules
* List of existings modules
* @type {Object}
*/
var modules = {};
Expand Down Expand Up @@ -51,6 +51,12 @@

waitingModules.unshift([name, deps, module]);

/**
* Uid for script differentiation
* @type {String}
*/
self.uid = Math.random().toString(36).replace(/[^a-z0-9]+/g, '').substr(0, 10);

self.checkModuleLoaded();

if (deps.length) {
Expand All @@ -74,6 +80,31 @@
}
}

/**
* Get element data id
* @param {String} name
* @param {Boolean} clean only clean the name
* @return {String}
*/
Include.prototype.getId = function (name, clean) {
return (clean ? '' : this.uid + '-') + name.replace(/[^a-z0-9]+/g, '');
}

/**
* Get current script name
* @return {String}
*/
Include.prototype.getFileName = function () {
var scripts = document.querySelectorAll('script'),
currentScript = scripts[scripts.length - 1],
currentPath = document.location.href.split('/'),
path = currentScript.src;

currentPath.pop();
currentPath = currentPath.join('/');
return path.replace(currentPath, '').substring(1);
};

/**
* Check if a module is loaded
*/
Expand All @@ -88,14 +119,15 @@

self.each(dependencies, function (dependencie, n, t) {
n = dependencie.push ? dependencie[0] : dependencie;
t = document.querySelector('[data-module="'+n+'"]');

if (modules[n] !== undefined) {
args.push(modules[n]);
}
t = document.querySelector('[data-id*="' + self.getId(n, 1) + '"]');

if (t && t.nodeName == "LINK") {
args.push(null);
return;
}

if (modules[n] !== undefined) {
args.push(modules[n]);
}
});

Expand All @@ -106,10 +138,7 @@
}

exec = typeof exec == 'function' ? exec.apply(this, args) : exec;

if (name !== null) {
modules[name] = exec;
}
modules[name || self.getFileName()] = exec;
}
});
}
Expand All @@ -118,9 +147,8 @@
* onModuleLoaded
* @param {String} name name of the module
* @param {Number} index index of the module
* @param {Boolean} isCss
*/
Include.prototype.onModuleLoaded = function (name, index, isCss) {
Include.prototype.onModuleLoaded = function (name, index) {
var self = this;

// Is this script add a waiting module ? If not, that's a "normal" script file
Expand Down Expand Up @@ -173,7 +201,7 @@
while (i--) {
if (sheets[i].href.indexOf(href) != -1) {
elem.setAttribute('data-loaded', true);
self.onModuleLoaded(elem.getAttribute('data-module'), elem.getAttribute('data-count'), true);
self.onModuleLoaded(elem.getAttribute('data-module'), elem.getAttribute('data-count'));

self.checkModuleLoaded();
return;
Expand Down Expand Up @@ -260,6 +288,7 @@
elem.rel = "stylesheet"
}

elem.setAttribute('data-id', self.getId(moduleName));
elem.setAttribute('data-module', moduleName);
elem.setAttribute('data-count', scriptCounter);
elem.setAttribute('data-loaded', false);
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "include.js",
"version": "3.0.0",
"version": "3.0.1",
"description": "**Include.js** is a tiny Javascript loader. It can load normal javascript files but is more efficient with **web modules**.",
"main": "include-min.js",
"dependencies": {},
Expand Down
36 changes: 25 additions & 11 deletions test/include-specs.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
describe("Replace define", function(){
it("include should replace Require and Define", function(){
var test = false;

if (require && define) {
test = true;
}

expect(test).toBe(true);
expect(include).toEqual(jasmine.any(Function));
expect(require).toEqual(jasmine.any(Function));
expect(define).toEqual(jasmine.any(Function));
});
});

Expand All @@ -26,6 +22,17 @@ describe("Normal script", function(){
done();
});
});

it("should be able to load script dependencies", function (done){
include(['https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.6.0/highlight.min.js'], function () {
expect(hljs).toEqual(jasmine.any(Object));

include(['https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.6.0/languages/javascript.min.js'], function () {
expect(hljs.listLanguages()).toContain("javascript");
done();
});
});
})
});

describe("Module name", function(){
Expand Down Expand Up @@ -84,9 +91,16 @@ describe("Include css", function(){
});
});

it("should be able to reload css", function(done){
include(['https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/4.1.0/sanitize.css'], function(css){
expect(css).toBe(null);
done();
});
});

it("should be able to load css and module", function(done){
inc = include([
'https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/4.1.0/sanitize.css',
include([
'https://cdnjs.cloudflare.com/ajax/libs/16pixels/0.1.6/16pixels.css',
'data/b.js'
], function(css, b){
expect(css).toBe(null);
Expand All @@ -96,8 +110,8 @@ describe("Include css", function(){
});

it("should be able to load css and script as module", function(done){
inc = include([
'https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/4.1.0/sanitize.css',
include([
'https://cdnjs.cloudflare.com/ajax/libs/1140/2.0/1140.css',
['stripe', 'https://js.stripe.com/v2/stripe.js']
], function(css, stripe){
expect(css).toBe(null);
Expand Down

0 comments on commit 2c984c4

Please sign in to comment.