Skip to content

Instantly share code, notes, and snippets.

@cobbweb
Created September 4, 2015 00:22
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 cobbweb/bdcc0e8576922c07c468 to your computer and use it in GitHub Desktop.
Save cobbweb/bdcc0e8576922c07c468 to your computer and use it in GitHub Desktop.
(function(window) {
'use strict';
window.SrcSet = {
/**
* Converts srcset value into JS objects
* e.g. './image1.jpg 1100w, ./image1_big.jpg 1500w, ./image1_small.jpg'
* yields:
* [
* { src: './image1.jpg', width: 1100 },
* { src: './image1_big.jpg', width: 1500 },
* { src: './image1_small.jpg' }
* ]
*/
parseSrcSet: function parseSrcSet(srcset) {
var SRC_SET = /\s*([^ ]+)(\s+(\d{1,5})w)?\s*/i
var _sources = srcset.split(',');
var sources = [];
for (var i = 0, len = _sources.length; i < len; i++) {
var results = SRC_SET.exec(_sources[i]);
if (results) {
var src = { src: results[1] };
if (results[3]) {
src.width = Number(results[3]);
}
sources.push(src);
}
}
return sources;
},
/**
* Queries a srcset object and finds the most suitable src
* based on the supplied width
*/
matchSource: function matchSource(sources, viewportWidth) {
// Width 6 million to to help with size matching later on
var matchedSource = { width: 6e6 };
var fallbackSource;
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
if (source.width) {
if (viewportWidth <= source.width && source.width < matchedSource.width) {
matchedSource = source;
}
} else {
fallbackSource = source;
}
}
// No source found for provided viewportHeight
// Fallback to a source that specified no width
if (!matchedSource.src) {
matchedSource = fallbackSource;
}
return matchedSource;
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment