Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ab-interchange

Package Overview
Dependencies
Maintainers
1
Versions
23
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ab-interchange - npm Package Compare versions

Comparing version 2.3.0 to 2.4.1

yarn.lock

113

dist/AB-interchange.js

@@ -136,4 +136,4 @@ /******/ (function(modules) { // webpackBootstrap

var AB = __webpack_require__(0);
var abMediaQuery = __webpack_require__(2);
var AB = __webpack_require__(0),
abMediaQuery = __webpack_require__(2);

@@ -173,4 +173,2 @@ var pluginName = 'interchange',

._updatePath();
return this;
},

@@ -273,64 +271,61 @@

window.dispatchEvent(event);
return this;
},
_replace: function() {
var that = this,
path = that.currentPath;
// if lazy load and not into view: stop
if (this.settings.lazy && !this._inView())
return this;
if ( !that.settings.lazy || (that.settings.lazy && that._inView()) ) {
// image case
if (that.mode === 'img') {
if (that.el.src === path)
return that;
if (this.mode === 'img') {
this._replaceImg();
} else if (this.mode === 'background') {
this._replaceBackground();
} else if (this.mode === 'ajax') {
this._replaceAjax();
}
},
that.el.src = path; // event triggered when img is loaded
return that;
}
_replaceImg: function() {
if (this.el.src === this.currentPath)
return this;
// background-image case
if (that.mode === 'background') {
if (that.el.style.backgroundImage === 'url("'+path+'")')
return that;
this.el.src = this.currentPath; // event triggered when img is loaded
this._triggerEvent();
},
if (path)
path = 'url('+path+')';
else
path = 'none';
_replaceBackground: function() {
if (this.el.style.backgroundImage === 'url("' + this.currentPath + '")')
return this;
that.el.style.backgroundImage = path;
that._triggerEvent();
if (this.currentPath)
this.el.style.backgroundImage = 'url(' + this.currentPath + ')';
else
this.el.style.backgroundImage = 'none';
return that;
}
this._triggerEvent();
},
// HTML case
if (that.mode === 'ajax') {
if (!path) {
that.el.innerHTML = '';
return that;
}
_replaceAjax: function () {
var that = this;
var request = new XMLHttpRequest();
request.open('GET', path, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
that.el.innerHTML = this.response;
that._triggerEvent();
} else {
that.el.innerHTML = '';
}
};
if (!this.currentPath) {
this.el.innerHTML = '';
return this;
}
request.onerror = function() {
that.el.innerHTML = '';
};
request.send();
return that;
var request = new XMLHttpRequest();
request.open('GET', this.currentPath, true);
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
that.el.innerHTML = this.response;
that._triggerEvent();
} else {
that.el.innerHTML = '';
}
};
return that;
}
request.onerror = function () {
this.el.innerHTML = '';
};
request.send();
}

@@ -347,2 +342,3 @@ };

/***/ }),

@@ -363,3 +359,3 @@ /* 2 */

this.init();
this._init();
};

@@ -372,3 +368,3 @@

Plugin.prototype = {
init: function() {
_init: function() {
this.current = this._getCurrent();

@@ -395,7 +391,5 @@ this._watcher();

_watcher: function() {
var that = this,
event = new CustomEvent('changed.ab-mediaquery'),
newSize, resizeTimer;
var that = this;
window.onresize = function() {
window.addEventListener('resize', function() {
if (!that.animated) {

@@ -405,3 +399,3 @@ window.requestAnimationFrame(that._updateSizes.bind(that));

}
};
});
},

@@ -431,3 +425,4 @@

/***/ })
/******/ ]);

@@ -1,1 +0,1 @@

!function(t){function e(i){if(n[i])return n[i].exports;var r=n[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,e),r.l=!0,r.exports}var n={};e.m=t,e.c=n,e.d=function(t,n,i){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,e){!function(){function t(t,e){e=e||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(t,e.bubbles,e.cancelable,e.detail),n}if("function"==typeof window.CustomEvent)return!1;t.prototype=window.Event.prototype,window.CustomEvent=t}(),window.AB={extend:function(){var t={},e=!1,n=0,i=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(e=arguments[0],n++);for(;n<i;n++)!function(n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e&&"[object Object]"===Object.prototype.toString.call(n[i])?t[i]=window.AB.extend(!0,t[i],n[i]):t[i]=n[i])}(arguments[n]);return t},isJson:function(t){try{JSON.parse(t)}catch(t){return!1}return!0},plugins:{}}},function(t,e,n){"use strict";var i=(n(0),n(2),"data-ab-interchange"),r=function(t,e){this.el=t;var n=window.AB.isJson(this.el.getAttribute(i))?JSON.parse(this.el.getAttribute(i)):{};this.settings=window.AB.extend(!0,r.defaults,e,n),this.rules=[],this.currentPath="",this.mode=this._defineMode(),this.animated=!1,this.init()};r.defaults={mode:"background",lazy:!0,offscreen:1.5},r.prototype={init:function(){return this.el.parentNode.matches("picture")&&window.HTMLPictureElement?this:(this._events()._generateRules()._updatePath(),this)},_defineMode:function(){return"IMG"===this.el.nodeName?"img":this.settings.mode},_generateRules:function(){for(var t=[],e=this.el.getAttribute("data-ab-interchange-src").match(/\[[^\]]+\]/g),n=0,i=e.length;n<i;n++){var r=e[n].slice(1,-1).split(", "),s=r.slice(0,-1).join(""),o=r[r.length-1];t.push({path:s,query:o})}return this.rules=t,this},_updatePath:function(){for(var t="",e=this.rules,n=0,i=e.length;n<i;n++)window.AB.mediaQuery.is(e[n].query)&&(t=e[n].path);return this.currentPath===t?this:(this.currentPath=t,this._replace(),this)},_onScroll:function(){return this.animated=!1,this._inView()&&this._replace(),this},_events:function(){var t=this;return window.addEventListener("changed.ab-mediaquery",t._updatePath.bind(t)),t.settings.lazy&&window.addEventListener("scroll",function(){t.animated||(window.requestAnimationFrame(t._onScroll.bind(t)),t.animated=!0)}),t.el.addEventListener("load",t._triggerEvent.bind(t)),t},_inView:function(){var t=window.innerHeight,e=this.el.getBoundingClientRect();return e.top>=-t*this.settings.offscreen&&e.bottom<=t+t*this.settings.offscreen},_triggerEvent:function(){var t=new CustomEvent("replaced.ab-interchange",{detail:{element:this.el}});return window.dispatchEvent(t),this},_replace:function(){var t=this,e=t.currentPath;if(!t.settings.lazy||t.settings.lazy&&t._inView()){if("img"===t.mode)return t.el.src===e?t:(t.el.src=e,t);if("background"===t.mode)return t.el.style.backgroundImage==='url("'+e+'")'?t:(e=e?"url("+e+")":"none",t.el.style.backgroundImage=e,t._triggerEvent(),t);if("ajax"===t.mode){if(!e)return t.el.innerHTML="",t;var n=new XMLHttpRequest;return n.open("GET",e,!0),n.onload=function(){this.status>=200&&this.status<400?(t.el.innerHTML=this.response,t._triggerEvent()):t.el.innerHTML=""},n.onerror=function(){t.el.innerHTML=""},n.send(),t}return t}}},window.abInterchange=function(t){for(var e=document.querySelectorAll("["+i+"]"),n=0,s=e.length;n<s;n++)e[n].interchange||(e[n].interchange=new r(e[n],t))}},function(t,e,n){"use strict";var i=(n(0),function(t){this.settings=window.AB.extend(!0,i.defaults,t),this.queries=this.settings.bp,this.current=[],this.animated=!1,this.init()});i.defaults={bp:{}},i.prototype={init:function(){return this.current=this._getCurrent(),this._watcher(),this},_getCurrent:function(){var t=[];for(var e in this.queries)this.queries.hasOwnProperty(e)&&window.matchMedia(this.queries[e]).matches&&t.push(e);return t},_watcher:function(){var t=this;new CustomEvent("changed.ab-mediaquery");window.onresize=function(){t.animated||(window.requestAnimationFrame(t._updateSizes.bind(t)),t.animated=!0)}},_updateSizes:function(){var t=this._getCurrent(),e=new CustomEvent("changed.ab-mediaquery");this.animated=!1,t.join("|")!==this.current.join("|")&&(this.current=t,window.dispatchEvent(e))},is:function(t){return window.matchMedia(this.queries[t]).matches}},window.abMediaQuery=function(t){window.AB.mediaQuery=new i(t)}}]);
!function(t){function e(i){if(n[i])return n[i].exports;var r=n[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,e),r.l=!0,r.exports}var n={};e.m=t,e.c=n,e.d=function(t,n,i){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,e){!function(){function t(t,e){e=e||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(t,e.bubbles,e.cancelable,e.detail),n}if("function"==typeof window.CustomEvent)return!1;t.prototype=window.Event.prototype,window.CustomEvent=t}(),window.AB={extend:function(){var t={},e=!1,n=0,i=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(e=arguments[0],n++);for(;n<i;n++)!function(n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e&&"[object Object]"===Object.prototype.toString.call(n[i])?t[i]=window.AB.extend(!0,t[i],n[i]):t[i]=n[i])}(arguments[n]);return t},isJson:function(t){try{JSON.parse(t)}catch(t){return!1}return!0},plugins:{}}},function(t,e,n){"use strict";var i=(n(0),n(2),"data-ab-interchange"),r=function(t,e){this.el=t;var n=window.AB.isJson(this.el.getAttribute(i))?JSON.parse(this.el.getAttribute(i)):{};this.settings=window.AB.extend(!0,r.defaults,e,n),this.rules=[],this.currentPath="",this.mode=this._defineMode(),this.animated=!1,this.init()};r.defaults={mode:"background",lazy:!0,offscreen:1.5},r.prototype={init:function(){if(this.el.parentNode.matches("picture")&&window.HTMLPictureElement)return this;this._events()._generateRules()._updatePath()},_defineMode:function(){return"IMG"===this.el.nodeName?"img":this.settings.mode},_generateRules:function(){for(var t=[],e=this.el.getAttribute("data-ab-interchange-src").match(/\[[^\]]+\]/g),n=0,i=e.length;n<i;n++){var r=e[n].slice(1,-1).split(", "),s=r.slice(0,-1).join(""),a=r[r.length-1];t.push({path:s,query:a})}return this.rules=t,this},_updatePath:function(){for(var t="",e=this.rules,n=0,i=e.length;n<i;n++)window.AB.mediaQuery.is(e[n].query)&&(t=e[n].path);return this.currentPath===t?this:(this.currentPath=t,this._replace(),this)},_onScroll:function(){return this.animated=!1,this._inView()&&this._replace(),this},_events:function(){var t=this;return window.addEventListener("changed.ab-mediaquery",t._updatePath.bind(t)),t.settings.lazy&&window.addEventListener("scroll",function(){t.animated||(window.requestAnimationFrame(t._onScroll.bind(t)),t.animated=!0)}),t.el.addEventListener("load",t._triggerEvent.bind(t)),t},_inView:function(){var t=window.innerHeight,e=this.el.getBoundingClientRect();return e.top>=-t*this.settings.offscreen&&e.bottom<=t+t*this.settings.offscreen},_triggerEvent:function(){var t=new CustomEvent("replaced.ab-interchange",{detail:{element:this.el}});window.dispatchEvent(t)},_replace:function(){if(this.settings.lazy&&!this._inView())return this;"img"===this.mode?this._replaceImg():"background"===this.mode?this._replaceBackground():"ajax"===this.mode&&this._replaceAjax()},_replaceImg:function(){if(this.el.src===this.currentPath)return this;this.el.src=this.currentPath,this._triggerEvent()},_replaceBackground:function(){if(this.el.style.backgroundImage==='url("'+this.currentPath+'")')return this;this.currentPath?this.el.style.backgroundImage="url("+this.currentPath+")":this.el.style.backgroundImage="none",this._triggerEvent()},_replaceAjax:function(){var t=this;if(!this.currentPath)return this.el.innerHTML="",this;var e=new XMLHttpRequest;e.open("GET",this.currentPath,!0),e.onload=function(){this.status>=200&&this.status<400?(t.el.innerHTML=this.response,t._triggerEvent()):t.el.innerHTML=""},e.onerror=function(){this.el.innerHTML=""},e.send()}},window.abInterchange=function(t){for(var e=document.querySelectorAll("["+i+"]"),n=0,s=e.length;n<s;n++)e[n].interchange||(e[n].interchange=new r(e[n],t))}},function(t,e,n){"use strict";var i=(n(0),function(t){this.settings=window.AB.extend(!0,i.defaults,t),this.queries=this.settings.bp,this.current=[],this.animated=!1,this._init()});i.defaults={bp:{}},i.prototype={_init:function(){return this.current=this._getCurrent(),this._watcher(),this},_getCurrent:function(){var t=[];for(var e in this.queries)this.queries.hasOwnProperty(e)&&window.matchMedia(this.queries[e]).matches&&t.push(e);return t},_watcher:function(){var t=this;window.addEventListener("resize",function(){t.animated||(window.requestAnimationFrame(t._updateSizes.bind(t)),t.animated=!0)})},_updateSizes:function(){var t=this._getCurrent(),e=new CustomEvent("changed.ab-mediaquery");this.animated=!1,t.join("|")!==this.current.join("|")&&(this.current=t,window.dispatchEvent(e))},is:function(t){return window.matchMedia(this.queries[t]).matches}},window.abMediaQuery=function(t){window.AB.mediaQuery=new i(t)}}]);
'use strict';
var AB = require('another-brick');
var abMediaQuery = require('ab-mediaquery');
var AB = require('another-brick'),
abMediaQuery = require('ab-mediaquery');

@@ -39,4 +39,2 @@ var pluginName = 'interchange',

._updatePath();
return this;
},

@@ -139,64 +137,61 @@

window.dispatchEvent(event);
return this;
},
_replace: function() {
var that = this,
path = that.currentPath;
// if lazy load and not into view: stop
if (this.settings.lazy && !this._inView())
return this;
if ( !that.settings.lazy || (that.settings.lazy && that._inView()) ) {
// image case
if (that.mode === 'img') {
if (that.el.src === path)
return that;
if (this.mode === 'img') {
this._replaceImg();
} else if (this.mode === 'background') {
this._replaceBackground();
} else if (this.mode === 'ajax') {
this._replaceAjax();
}
},
that.el.src = path; // event triggered when img is loaded
return that;
}
_replaceImg: function() {
if (this.el.src === this.currentPath)
return this;
// background-image case
if (that.mode === 'background') {
if (that.el.style.backgroundImage === 'url("'+path+'")')
return that;
this.el.src = this.currentPath; // event triggered when img is loaded
this._triggerEvent();
},
if (path)
path = 'url('+path+')';
else
path = 'none';
_replaceBackground: function() {
if (this.el.style.backgroundImage === 'url("' + this.currentPath + '")')
return this;
that.el.style.backgroundImage = path;
that._triggerEvent();
if (this.currentPath)
this.el.style.backgroundImage = 'url(' + this.currentPath + ')';
else
this.el.style.backgroundImage = 'none';
return that;
}
this._triggerEvent();
},
// HTML case
if (that.mode === 'ajax') {
if (!path) {
that.el.innerHTML = '';
return that;
}
_replaceAjax: function () {
var that = this;
var request = new XMLHttpRequest();
request.open('GET', path, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
that.el.innerHTML = this.response;
that._triggerEvent();
} else {
that.el.innerHTML = '';
}
};
if (!this.currentPath) {
this.el.innerHTML = '';
return this;
}
request.onerror = function() {
that.el.innerHTML = '';
};
request.send();
return that;
var request = new XMLHttpRequest();
request.open('GET', this.currentPath, true);
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
that.el.innerHTML = this.response;
that._triggerEvent();
} else {
that.el.innerHTML = '';
}
};
return that;
}
request.onerror = function () {
this.el.innerHTML = '';
};
request.send();
}

@@ -211,2 +206,2 @@ };

}
};
};
{
"name": "ab-interchange",
"version": "2.3.0",
"version": "2.4.1",
"description": "AB-interchange: While responsive image loading is not really an easy task even today, here is a solution to manage conditional (based on breakpoints) loading of img, background-image or even HTML content.",

@@ -22,3 +22,2 @@ "main": "index.js",

"breakpoint",
"jQuery",
"ajax",

@@ -34,3 +33,3 @@ "img",

"dependencies": {
"ab-mediaquery": "^2.6.0",
"ab-mediaquery": "^2.6.1",
"another-brick": "^1.2.0"

@@ -37,0 +36,0 @@ },

# AB-interchange
AB-interchange is a vanilla JavaScript that makes possible conditionnaly loading depending on media queries:
AB-interchange is a small, dependencie free and vanilla JavaScript component that conditionnaly load things depending on media queries and it also has a **lazy-loading** option:
- **img** (it can be also used as a **picture** polyfill on unsupported browsers)
- **img**
- **picture**
- **background-image**
- **HTML content** (Ajax)
It's damn small: about **1800 bytes** (uglyfied and GZipped).
It's damn small: about **1800 bytes** (uglyfied and GZipped). It is used in the French website of [ENGIE](https://particuliers.engie.fr).
That plugin also has an **lazy-loading** option!
Have a look at the [Codepen demonstration](https://codepen.io/lordfpx/pen/jApqLW).
- [codepen](https://codepen.io/lordfpx/pen/jApqLW)
- [NPM](https://www.npmjs.com/package/ab-interchange)
[![Maintainability](https://api.codeclimate.com/v1/badges/85a4444c8e573ae62a49/maintainability)](https://codeclimate.com/github/lordfpx/AB-interchange/maintainability)
```
> npm install ab-interchange
```
or
```
> yarn add ab-interchange
```
It's used on French website [ENGIE](https://particuliers.engie.fr/).
## Install
---
Install with npm:
```bash
npm install --save ab-interchange
````
## Setup
Install with yarn:
```bash
yarn add ab-interchange
```
### Classic usage
Just load the script on your page, just before `</body>`.
**No need to load [another-brick](https://github.com/lordfpx/AB) or [AB-mediaQuery](https://github.com/lordfpx/AB-mediaQuery) since they are already included into AB-interchange. You can use their features of course (read respective readme).**
## Setup
### As a module
The best solution is to use browserify or Webpack and import 'abInterchange'.
```
You can then import it in your JS bundle (webpack, ES6, browserify...):
```js
import abInterchange from 'ab-interchange';
```
---
Or loading the js right before `</body>` if you are not using a builder.
## Compatibility
Because of the usage of `matchMedia` and `requestAnimationFrame`, compatibility start with IE 10. To rise compatibility up to IE 9, you can add [matchMedia polyfill](https://github.com/paulirish/matchMedia.js/) and [requestAnimationFrame polyfill](https://gist.github.com/paulirish/1579671).
---

@@ -54,3 +46,3 @@ ## Usage

```
```js
abMediaQuery({

@@ -69,3 +61,3 @@ bp: {

```
```js
abInterchange({

@@ -77,14 +69,23 @@ lazy : true, // or false

Then use **data-ab-interchange** attribute to pass otpions individually.
Then use `data-ab-interchange` attribute to pass options.
**data-ab-interchange-src** attribute is where you define different sources and breakpoints defined with AB-mediaQuery.
`data-ab-interchange-src` attribute is where you define different sources and breakpoints defined with AB-mediaQuery.
It should contain a list of arrays with the path to the asset and the breakpoint name. Beware to respect mobile first order. Order is **VERY** important!
---
## Examples
### **img**
```html
<img
alt=""
data-ab-interchange='{"lazy": false}"'
data-ab-interchange-src="[xxx, smallOnly], [xxx, medium]"/>
```
### **picture**
```
```html
<picture>

@@ -97,3 +98,3 @@ <source srcset="xxx" media="(min-width: 80em)"/>

alt=""
data-ab-interchange='{"lazy": false}"
data-ab-interchange='{"lazy": false}"'
data-ab-interchange-src="[xxx, smallOnly], [xxx, medium]"/>

@@ -103,17 +104,8 @@ </picture>

### **img**
```
<img
alt=""
data-ab-interchange='{"lazy": false}"
data-ab-interchange-src="[xxx, smallOnly], [xxx, medium]"/>
```
### **background-image**
```
```html
<div
data-ab-interchange='{"mode": "background", "lazy": true, "offscreen": 1.5}"
data-ab-interchange='{"mode": "background", "lazy": true, "offscreen": 1.5}"'
data-ab-interchange-src="[xxx, smallOnly], [xxx, medium]">

@@ -124,7 +116,7 @@ </div>

### **and even XMLHttpRequest content (ajax)!**
### **XMLHttpRequest content (Ajax)**
```
```html
<div
data-ab-interchange="{"mode": "ajax", "lazy": false}"
data-ab-interchange='{"mode": "ajax", "lazy": false}'
data-ab-interchange-src="[xxx, smallOnly], [xxx, mediumOnly]">

@@ -135,9 +127,9 @@ </div>

### JS event
'replaced.ab-interchange' event is automatically triggered when an IMG (or else) changed. **For IMG and HTML, it's fired only when the new content is loaded**, for background-image, immediatly, because it does not impact the layout:
## JS event
`replaced.ab-interchange` event is automatically triggered when an IMG (or else) changed. **For IMG and HTML, it's fired only when the new content is loaded**, for background-image, immediatly, because it does not impact the layout:
```
```js
window.addEventListener('replaced.ab-interchange', function(e){
console.log(e.detail.element);
});
```
```

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc