Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.