Permalink
Browse files

Fixes some issues with picture that have to do with the latest spec

  • Loading branch information...
1 parent 3af2df1 commit e9d802d8fca07b5ee89ed9c7c4ea490c235bb007 @jansepar jansepar committed Oct 20, 2014
View
@@ -5,7 +5,7 @@
"dependencies": {
"mobifyjs-utils": "git@github.com:mobify/mobifyjs-utils.git#1.0.0",
"jazzcat-client": "git@github.com:mobify/jazzcat-client.git#1.0.0",
- "imageresize-client": "git@github.com:mobify/imageresize-client.git#1.0.2"
+ "imageresize-client": "git@github.com:mobify/imageresize-client.git#rewrite-srcset"
},
"devDependencies": {
View
@@ -158,20 +158,27 @@ ResizeImages.getImageURL = function(url, options) {
*/
ResizeImages._rewriteSrcAttribute = function(element, opts, srcVal){
- srcVal = element.getAttribute(opts.sourceAttribute) || srcVal;
+ srcVal = element.getAttribute(opts.sourceAttribute) ||
+ element.getAttribute(opts.sourceSetAttribute) ||
+ srcVal;
if (srcVal) {
var url = Utils.absolutify(srcVal);
if (Utils.httpUrl(url)) {
if (opts.onerror) {
element.setAttribute('onerror', opts.onerror);
}
- element.setAttribute(opts.targetAttribute, ResizeImages.getImageURL(url, opts));
+ // if the element is a source element, then we always want to set srcset rather then src
+ var targetAttribute = (element.nodeName === 'SOURCE') ? opts.targetSrcSetAttribute : opts.targetSrcAttribute;
+
+ element.setAttribute(targetAttribute, ResizeImages.getImageURL(url, opts));
element.setAttribute('data-orig-src', srcVal);
// if using resize when not capturing, remove the sourceAttribute
- // as long as it's not "src", which is the target attribute used
- // when not capturing.
- if (!capturing && opts.sourceAttribute != opts.targetAttribute) {
+ // or sourceSetAttribute as long as it's not "src", which is the target
+ // attribute used when not capturing.
+ if (!capturing && opts.sourceAttribute != opts.targetSrcAttribute) {
element.removeAttribute(opts.sourceAttribute);
+ } else if (!capturing && opts.sourceSetAttribute != opts.targetSrcSetAttribute) {
+ element.removeAttribute(opts.sourceSetAttribute);
}
}
}
@@ -362,11 +369,14 @@ ResizeImages.resize = function(elements, options) {
}
var opts = ResizeImages.processOptions(options);
- for(var i=0; i < elements.length; i++) {
+ for (var i=0; i < elements.length; i++) {
var element = elements[i];
-
// For an `img`, simply modify the src attribute
if (element.nodeName === 'IMG' && !element.hasAttribute('mobify-optimized')) {
+ // Skip this image if it's parent is a picture element
+ if (element.parentNode && element.parentNode.nodeName === 'PICTURE') {
+ continue;
+ }
element.setAttribute('mobify-optimized', '');
ResizeImages._rewriteSrcAttribute(element, opts);
}
@@ -397,7 +407,9 @@ ResizeImages.defaults = {
host: 'ir0.mobify.com',
projectName: "oss-" + location.hostname.replace(/[^\w]/g, '-'),
sourceAttribute: "x-src",
- targetAttribute: (capturing ? "x-src" : "src"),
+ sourceSetAttribute: "x-srcset",
+ targetSrcAttribute: (capturing ? "x-src" : "src"),
+ targetSrcSetAttribute: (capturing ? "x-srcset" : "srcset"),
webp: ResizeImages.supportsWebp(),
resize: true,
onerror: 'ResizeImages.restoreOriginalSrc(event);'
@@ -1419,8 +1431,8 @@ var tagEnablingRe = new RegExp(Utils.values(tagDisablers).join('|'), 'g');
// Map of all attributes we should disable (to prevent resources from downloading)
var disablingMap = {
- img: ['src'],
- source: ['src'],
+ img: ['src', 'srcset'],
+ source: ['src', 'srcset'],
iframe: ['src'],
script: ['src', 'type'],
link: ['href'],
@@ -2127,7 +2139,6 @@ return CssOptimize;
require('../capture.js'));
}
}(this, function (Utils, Capture) {
-
var capturing = window.Mobify && window.Mobify.capturing || false;
if (capturing) {
@@ -2208,7 +2219,7 @@ window.matchMedia = window.matchMedia || Utils.matchMedia(document);
if( matches.length ){
// Grab the most appropriate (last) match.
- var match = matches.pop(),
+ var match = matches[0],
srcset = match.getAttribute( "srcset" );
if( !picImg ){
@@ -2226,7 +2237,11 @@ window.matchMedia = window.matchMedia || Utils.matchMedia(document);
for( var res = sources.length, r = res - 1; r >= 0; r-- ) { // Loop through each source/resolution in `srcset`.
var source = sources[ r ].replace(/^\s*/, '').replace(/\s*$/, '').split(" "), // Remove any leading whitespace, then split on spaces.
resMatch = parseFloat( source[1], 10 ); // Parse out the resolution for each source in `srcset`.
-
+ if (isNaN(resMatch)) {
+ // this srcset doesn't have a resolution specified, so just set the src.
+ picImg.src = match.getAttribute( "srcset" );
+ break;
+ }
if( screenRes >= resMatch ) {
if( picImg.getAttribute( "src" ) !== source[0] ) {
var newImg = document.createElement("img");
View
Oops, something went wrong.
@@ -4,36 +4,62 @@
<title>Mobify.js Image Resizer Without Capturing</title>
<link rel="stylesheet" href="/mobifyjs/examples/assets/css/stylesheet.css" type="text/css">
-<style>
-.images {
- width: 1024px;
-}
-.images img {
- width: 49%;
-}
-</style>
<script async src="/mobifyjs/build/mobify.min.js"></script>
<script>
var intervalId = setInterval(function(){
if (window.Mobify) {
- var images = document.querySelectorAll('img[x-src]');
+ var images = document.querySelectorAll('img, picture');
if (images.length > 0) {
- Mobify.ResizeImages.resize( images, {
- maxWidth: 320
- });
+ Mobify.ResizeImages.resize( images );
}
// When the document has finished loading, stop checking for new images
if (Mobify.Utils.domIsReady()) {
clearInterval(intervalId)
}
}
- }, 30);
+ }, 100);
</script>
+<style>
+img {
+ max-width: 100%;
+}
+picture {
+ display: block;
+ padding: 1em;
+}
+.example-photo {
+ max-width: 100%;
+}
+@media (min-width: 512px) {
+ .example-photo {
+ float: left;
+ max-width: 50%;
+ }
+}
+</style>
</head>
<body class="foo">
-<div class="images">
- <img x-src="/mobifyjs/examples/assets/images/forest.jpg">
- <img x-src="/mobifyjs/examples/assets/images/mountains.jpg">
-</div>
+ <p>Picture element is used here in a much simpler way. Equivalent images at different breakpoints do not need to be automatically generated, they only need to set width attributes for each `source` element.</p>
+ <p>View the source to have a look, and view the inspector to see what the `resize` method does to the picture element's markup.</p>
+ <!-- http://upload.wikimedia.org/wikipedia/commons/6/68/President_Barack_Obama_Tours_Storm_Damage_in_New_Jersey_2.jpg -->
+ <picture class="example-photo" data-src="/mobifyjs/examples/assets/images/responsive-obama.jpg">
+ <source media="(min-width: 2048px)" data-width="1024">
+ <source media="(min-width: 1024px)" data-width="512">
+ <source media="(min-width: 512px)">
+ <source srcset="/mobifyjs/examples/assets/images/responsive-obama-mobile.png">
+ <img x-src="/mobifyjs/examples/assets/images/responsive-obama.jpg">
+ </picture>
+
+ <h1>Excitingus Headlineus</h1>
+
+ <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam viverra vestibulum mi, vitae euismod libero vehicula non. Morbi sollicitudin nulla in metus tincidunt lobortis. Cras volutpat eros sapien, vitae tempor arcu faucibus at. Sed a accumsan purus. Nulla eget sem lectus. Nullam pharetra lobortis eleifend. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed vel ligula velit. Integer eget sodales lacus, rutrum blandit dui.</p>
+
+ <p>Quisque pharetra augue id vehicula vulputate. Quisque volutpat dui nec vehicula hendrerit. Vivamus semper quam enim, vitae molestie enim luctus non. Fusce ornare nisi non arcu volutpat vestibulum. Aliquam quis neque quis metus pretium auctor. Cras vitae felis et odio auctor ornare sed a augue. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut accumsan tincidunt sapien. Donec volutpat erat at diam facilisis, eget tempus quam pharetra.</p>
+
+ <p>Mauris vulputate diam ac ante scelerisque, sed sodales turpis mattis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed purus justo, facilisis sed mauris et, tempus auctor mi. Sed ac interdum magna. Pellentesque id odio a lectus dapibus pharetra nec vitae urna. Suspendisse rutrum, odio a bibendum semper, velit augue fringilla augue, a rutrum ligula tellus non lorem. Donec quis felis nec nisi venenatis scelerisque.</p>
+
+ <p>Sed at aliquam mauris. Vestibulum aliquet, risus in bibendum mollis, nibh lectus gravida nunc, at condimentum metus arcu vel mi. Morbi id egestas erat. Sed vitae nisl molestie, dictum ante a, ultrices magna. Ut euismod accumsan sagittis. Vivamus porta nibh quis erat suscipit, vel consectetur tellus ultricies. Donec aliquam ornare congue. Cras lobortis purus nec nisl laoreet sodales. Proin sit amet mi vel urna vehicula ultrices non et mauris. Mauris ante dui, consectetur et tincidunt sed, bibendum in elit. Pellentesque volutpat hendrerit nisi a lacinia. Cras cursus in dui id porta.</p>
+
+ <p>Aliquam erat volutpat. Duis odio felis, consectetur sit amet libero et, rhoncus lacinia lacus. Vestibulum et magna sit amet tortor hendrerit lacinia posuere sit amet nunc. Proin hendrerit gravida molestie. Vivamus sit amet velit a ligula pellentesque pretium. Suspendisse viverra malesuada purus aliquam venenatis. Nunc tempor varius lectus, eget eleifend orci condimentum quis. Suspendisse pharetra, odio id rhoncus pharetra, mauris eros consequat enim, ac feugiat tellus augue a urna. Proin hendrerit dapibus felis iaculis tincidunt.</p>
</body>
</html>
@@ -49,10 +49,10 @@
<p>View the source to have a look, and view the inspector to see what the `resize` method does to the picture element's markup.</p>
<!-- http://upload.wikimedia.org/wikipedia/commons/6/68/President_Barack_Obama_Tours_Storm_Damage_in_New_Jersey_2.jpg -->
<picture class="example-photo" data-src="/mobifyjs/examples/assets/images/responsive-obama.jpg">
- <source src="/mobifyjs/examples/assets/images/responsive-obama-mobile.png">
- <source media="(min-width: 512px)">
- <source media="(min-width: 1024px)" data-width="512">
<source media="(min-width: 2048px)" data-width="1024">
+ <source media="(min-width: 1024px)" data-width="512">
+ <source media="(min-width: 512px)">
+ <source srcset="/mobifyjs/examples/assets/images/responsive-obama-mobile.png">
<img src="/mobifyjs/examples/assets/images/responsive-obama.jpg">
</picture>
View
@@ -37,8 +37,8 @@ var tagEnablingRe = new RegExp(Utils.values(tagDisablers).join('|'), 'g');
// Map of all attributes we should disable (to prevent resources from downloading)
var disablingMap = {
- img: ['src'],
- source: ['src'],
+ img: ['src', 'srcset'],
+ source: ['src', 'srcset'],
iframe: ['src'],
script: ['src', 'type'],
link: ['href'],
@@ -10,7 +10,6 @@
require('../capture.js'));
}
}(this, function (Utils, Capture) {
-
var capturing = window.Mobify && window.Mobify.capturing || false;
if (capturing) {
@@ -90,8 +89,8 @@ window.matchMedia = window.matchMedia || Utils.matchMedia(document);
picImg = ps[ i ].getElementsByTagName( "img" )[ 0 ];
if( matches.length ){
- // Grab the most appropriate (last) match.
- var match = matches.pop(),
+ // Grab the most appropriate (first) match.
+ var match = matches[0],
srcset = match.getAttribute( "srcset" );
if( !picImg ){
@@ -109,7 +108,11 @@ window.matchMedia = window.matchMedia || Utils.matchMedia(document);
for( var res = sources.length, r = res - 1; r >= 0; r-- ) { // Loop through each source/resolution in `srcset`.
var source = sources[ r ].replace(/^\s*/, '').replace(/\s*$/, '').split(" "), // Remove any leading whitespace, then split on spaces.
resMatch = parseFloat( source[1], 10 ); // Parse out the resolution for each source in `srcset`.
-
+ if (isNaN(resMatch)) {
+ // this srcset doesn't have a resolution specified, so just set the src.
+ picImg.src = match.getAttribute( "srcset" );
+ break;
+ }
if( screenRes >= resMatch ) {
if( picImg.getAttribute( "src" ) !== source[0] ) {
var newImg = document.createElement("img");

0 comments on commit e9d802d

Please sign in to comment.