Skip to content

Instantly share code, notes, and snippets.

@chrisboakes
Last active January 24, 2018 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisboakes/700d22509d6cc7bce52393fc8250dbc5 to your computer and use it in GitHub Desktop.
Save chrisboakes/700d22509d6cc7bce52393fc8250dbc5 to your computer and use it in GitHub Desktop.
Polyfill for browsers that do not support 'object-fit'
/**
* Polyfill for browsers that do not support 'object-fit'
* Replaces any image with a 'data-object-fit' attribute with a div with a background-image
* @author Chris Boakes & Gemma Black
*/
export class ObjectFitPolyfill {
constructor() {
this.dataSelector = '[data-object-fit]';
this.backgroundSize = 'cover';
this.cssClass = 'u-fill-image';
if (!this.supportsObjectFit()) {
this.findImages();
}
}
/**
* Find images, loop through them and replace with a div
*/
findImages() {
[].slice.call(document.querySelectorAll(this.dataSelector)).forEach((item) => {
if (item.getAttribute('src')) {
let backgroundElement = this.createBackground(
item.getAttribute('src'),
item.getAttribute('class'),
item.getAttribute('id')
);
item.parentNode.replaceChild(backgroundElement, item);
}
});
}
/**
* Our background-image container
* @param {string} src
* @param {string} tagClasses
* @param {string} tagId
* @return DOM element
*/
createBackground(src, tagClasses, tagId) {
let backgroundElement = document.createElement('div');
backgroundElement.style.backgroundImage = `url(${src})`;
backgroundElement.style.backgroundSize = this.backgroundSize;
backgroundElement.setAttribute('class', tagClasses + ' ' + this.cssClass)
if (tagId) {
backgroundElement.id = tagId;
}
return backgroundElement;
}
/**
* Detect whether we support object fit
* @return Boolean
*/
supportsObjectFit() {
let testImg = typeof Image === 'undefined' ? {style: {'object-position': 1}} : new Image();
return 'object-fit' in testImg.style;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment