Fixing Picturefill Firefox Bug

Firstly if you do not know what picturefill is I highly recommend checking it out here. I use picturefill a lot as I think it is fantastic and works generally really well. However recently when testing my site I was using firefox 38 and noticed that the slider I was using picturefill on was not responding correctly, if I shrunk in the screen it was not swapping out the image to a smaller version.

On reload it worked absoultely fine but it was just not working on the window resize. I assumed at first it was a clash with the owl carousel plugin I was using so I tried to debug that but I was not getting any errors or any problems at all. So I went back to the beginning again and used the demo files you get with the download of picturefill. To my surprise actually demo 3, the version I was using for picturefill as it worked best with my set up and cross browser, did not work correctly either.

I began my investigation searching through the bug list and any other places I could but nothing was really giving away what the problem could be, most people expected the same as me some errors to be able to debug. Then I found this plugin called lazysizes. It is a tiny script that fixes the little bug in Firefox and makes picturefill react correctly on screen resize. Of course you can include it as a separate script but what I did was minify it and added it to the top of the picturefill plugin and it works perfectly!

Here is the script in simple code format if you would rather just copy and paste:

/**
 * FF's first picture implementation is static and does not react to viewport changes, this tiny script fixes this.
 */
(function(){
	/*jshint eqnull:true */
	var ua = navigator.userAgent;

	if(window.HTMLPictureElement && ((/ecko/).test(ua) && ua.match(/rv\:(\d+)/) && RegExp.$1 < 41)){
		addEventListener('resize', (function(){
			var timer;

			var dummySrc = document.createElement('source');

			var fixPicture = function(img){
				var picture = img.parentNode;
				var source = dummySrc.cloneNode();
				picture.insertBefore(source, picture.firstElementChild);
				setTimeout(function(){
					picture.removeChild(source);
				});
			};

			var findPictureImgs = function(){
				var i;
				var imgs = document.querySelectorAll('picture > img');
				for(i = 0; i < imgs.length; i++){
					if(imgs[i].complete){
						if(imgs[i].currentSrc){
							fixPicture(imgs[i]);
						}
					} else if(imgs[i].currentSrc){
						removeEventListener('resize', onResize);
						break;
					}
				}
			};
			var onResize = function(){
				clearTimeout(timer);
				timer = setTimeout(findPictureImgs, 99);
			};

			dummySrc.srcset = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';

			return onResize;
		})());
	}
})();

I hope that can help a lot of you with a quick simple fix for those pesky little bugs that can leave you completely perplexed!