This solution works with Webpack and achieves the same functionality as the Recommended Usage in Example 1 above.
It seems that picturefill()
will be initialized during the first render (Without the src defined) and then skipped during the second render (With the src defined).
So… preventing the rendering of the picture element, up until you have the data, seems to work.
componentDidUpdate: function () {
picturefill();
},
render: function () {
return (
<div>
{(function () {
// You get the idea…
if (this.props.large === undefined) {
return '';
}
return (
<picture>
<!-- You get the idea… -->
<source srcSet={this.props.large} media="(min-width: 1024px)" />
<source srcSet={this.props.medium} media="(min-width: 640px)" />
<img srcSet={this.props.small} />
</picture>
);
}.bind(this)())}
</div>
);
}
- Works in Safari 8.0.8
- Works in Chrome 45
- Works in Firefox 40.0.3 (Only on refresh, not on resize)
UPDATE: 4/28/16
Now using isomorphic rendering with React so this solution doesn't work for me.
- Cannot
import 'picturefill';
due to dependency on window
which is not available in node.
picturefill();
, see below, does not work within componentDidUpdate
for Safari (9.0.3).
<picture>
strategy previously described did not work for me due to flash of wrong image (fowi).
/**
* OLD
*/
export class MyComponent extends Component {
componentDidMount() {
// TODO: remove when updated https://github.com/scottjehl/picturefill/pull/556
const picturefill = require('picturefill');
picturefill();
}
}
/**
* NEW
*/
// TODO: remove when updated https://github.com/scottjehl/picturefill/pull/556
if (__CLIENT__) {
require('picturefill');
require('picturefill/dist/plugins/mutation/pf.mutation'); // not sure if this does anything
}
export class MyComponent extends Component {}
Picture has been updated to the following:
<picture>
<source media="(min-width: 640px)" srcSet={'...'} />
<source srcSet={'...'} />
{/* SEE: http://scottjehl.github.io/picturefill/#fowi-safari */}
<img alt={title} />
</picture>
For Safari, flash of content still exists... But now shows the alt text...
As for require('picturefill/dist/plugins/mutation/pf.mutation');
:
This plugin automatically detects any DOM mutation and polyfills new or changed responsive images automatically. It also adds support for responsive images IDL attributes/properties. If you have a highly dynamic website or a SPA you probably want to use this plugin. (This plugin does not work with IE8.)