Skip to content

Commit

Permalink
picturefill vs picturePolyfill now with external scripts load
Browse files Browse the repository at this point in the history
  • Loading branch information
verlok committed Mar 9, 2014
1 parent 471fc28 commit 5b1e805
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 226 deletions.
65 changes: 65 additions & 0 deletions tests/js/picturefill.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
(function(){

// Enable strict mode
"use strict";

window.picturefill = function() {
var ps = window.document.getElementsByTagName( "span" );

// Loop the pictures
for( var i = 0, il = ps.length; i < il; i++ ){
if( ps[ i ].getAttribute( "data-picturefill" ) !== null ){

var sources = ps[ i ].getElementsByTagName( "span" ),
matches = [];

// See if which sources match
for( var j = 0, jl = sources.length; j < jl; j++ ){
var media = sources[ j ].getAttribute( "data-media" );
// if there's no media specified, OR window.matchMedia is supported
if( !media || ( window.matchMedia && window.matchMedia( media ).matches ) ){
matches.push( sources[ j ] );
}
}

// Find any existing img element in the picture element
var picImg = ps[ i ].getElementsByTagName( "img" )[ 0 ];

if( matches.length ){
var matchedEl = matches.pop();
if( !picImg || picImg.parentNode.nodeName === "NOSCRIPT" ){
picImg = window.document.createElement( "img" );
picImg.alt = ps[ i ].getAttribute( "data-alt" );
}
else if( matchedEl === picImg.parentNode ){
// Skip further actions if the correct image is already in place
continue;
}

picImg.src = matchedEl.getAttribute( "data-src" );
matchedEl.appendChild( picImg );
picImg.removeAttribute("width");
picImg.removeAttribute("height");
}
else if( picImg ){
picImg.parentNode.removeChild( picImg );
}
}
}
};

// Run on resize and domready (window.load as a fallback)
if( window.addEventListener ){
window.addEventListener( "resize", window.picturefill, false );
window.addEventListener( "DOMContentLoaded", function(){
window.picturefill();
// Run once only
window.removeEventListener( "load", window.picturefill, false );
}, false );
window.addEventListener( "load", window.picturefill, false );
}
else if( window.attachEvent ){
window.attachEvent( "onload", window.picturefill );
}

}());
229 changes: 3 additions & 226 deletions tests/picturefill_vs_picturePolyfill.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,232 +4,6 @@
<title>Hey</title>
</head>
<body>

<script>

/*! Picturefill - Responsive Images that work today. (and mimic the proposed Picture element with span elements). Author: Scott Jehl, Filament Group, 2012 | License: MIT/GPLv2 */

(function(){

// Enable strict mode
"use strict";

window.picturefill = function() {
var ps = window.document.getElementsByTagName( "span" );

// Loop the pictures
for( var i = 0, il = ps.length; i < il; i++ ){
if( ps[ i ].getAttribute( "data-picturefill" ) !== null ){

var sources = ps[ i ].getElementsByTagName( "span" ),
matches = [];

// See if which sources match
for( var j = 0, jl = sources.length; j < jl; j++ ){
var media = sources[ j ].getAttribute( "data-media" );
// if there's no media specified, OR window.matchMedia is supported
if( !media || ( window.matchMedia && window.matchMedia( media ).matches ) ){
matches.push( sources[ j ] );
}
}

// Find any existing img element in the picture element
var picImg = ps[ i ].getElementsByTagName( "img" )[ 0 ];

if( matches.length ){
var matchedEl = matches.pop();
if( !picImg || picImg.parentNode.nodeName === "NOSCRIPT" ){
picImg = window.document.createElement( "img" );
picImg.alt = ps[ i ].getAttribute( "data-alt" );
}
else if( matchedEl === picImg.parentNode ){
// Skip further actions if the correct image is already in place
continue;
}

picImg.src = matchedEl.getAttribute( "data-src" );
matchedEl.appendChild( picImg );
picImg.removeAttribute("width");
picImg.removeAttribute("height");
}
else if( picImg ){
picImg.parentNode.removeChild( picImg );
}
}
}
};

// Run on resize and domready (window.load as a fallback)
if( window.addEventListener ){
window.addEventListener( "resize", window.picturefill, false );
window.addEventListener( "DOMContentLoaded", function(){
window.picturefill();
// Run once only
window.removeEventListener( "load", window.picturefill, false );
}, false );
window.addEventListener( "load", window.picturefill, false );
}
else if( window.attachEvent ){
window.attachEvent( "onload", window.picturefill );
}

}());


// -------------------------------------------------------------------------------------------------------------------

/* PicturePolyfill - Responsive Images that work today. (and mimic the proposed Picture element with span elements). Author: Andrea Verlicchi | License: MIT/GPLv2 */

(function() {

"use strict";

var timerId,
pixelRatio = window.devicePixelRatio || 1, // The pixel density (2 is for HD aka Retina displays)
mediaQueriesSupported = window.matchMedia && window.matchMedia("only all") !== null && window.matchMedia("only all").matches;


/**
* Returns the proper src from the srcSet property
* If arrayOrString is a string, returns it
* else get the first valid element from passed position to the left
* @param arrayOrString
* @param position
* @returns {*}
*/

function getSrcFromSrcSet(arrayOrString, position) {
if (typeof arrayOrString === 'string') {
return arrayOrString;
}
while (arrayOrString[position]==null && position>0) {
position-=1;
}
return arrayOrString[position];
}


/**
* Loop through every element of the dataPicture array, check if the media query applies and,
* if so, get the src element from the srcSet property based depending on pixel ratio
* @param dataPicture
* @returns {string}
*/

function getSrcAttributeFromData(dataPicture) {
var media, matchedSrc;

for (var i=0, len=dataPicture.length; i<len; i+=1) {
media = dataPicture[i].media;
if (!media || window.matchMedia(media).matches) {
matchedSrc = getSrcFromSrcSet(dataPicture[i].srcset, pixelRatio-1);
}
}
return matchedSrc;
}


/**
* Search for the "standard: true" image in the array
* @param dataPicture
* @returns {string}
*/

function getStandardImageFromData(dataPicture) {
var dataElement;

for (var i=0, len=dataPicture.length; i<len; i+=1) {
dataElement = dataPicture[i];
if (dataElement.standard) {
break;
}
}
return getSrcFromSrcSet(dataElement.srcset, 0);
}

/**
* Set the src attribute of the first image element inside passed imageHolder
* if the image doesn't exist, creates it, sets its alt attribute, and appends it to imageHolder
* @param imageHolder
* @param srcAttribute
*/

function createOrUpdateImage(imageHolder, srcAttribute) {
var imageElements, imageElement;
imageElements = imageHolder.getElementsByTagName('img');

// If image already exist, use it
if (imageElements.length) {
imageElements[0].setAttribute('src', srcAttribute);
}
// Else create the image
else {
imageElement = document.createElement('img');
imageElement.setAttribute('alt', imageHolder.getAttribute('data-alt'));
imageElement.setAttribute('src', srcAttribute);
imageHolder.appendChild(imageElement);
}
}

/**
* Parses the DOM looking for elements containing the "data-picture" attribute, then
* generate the images or updates their src attribute.
* @param element the starting element to parse DOM into. If not passed, it parses the whole document.
*/

function parseDOM(element) {

var pictureData, imageHolder,
imageHolders = (element || document).querySelectorAll('[data-picture]');

// Finding all the elements with data-image
for (var i=0, len=imageHolders.length; i<len; i+=1) {
imageHolder = imageHolders[i];
try {
pictureData = JSON.parse(imageHolder.getAttribute('data-picture'));
// Take the source from the matched media, or standard media
// Update the image, or create it
createOrUpdateImage(imageHolder, (mediaQueriesSupported) ?
getSrcAttributeFromData(pictureData) :
getStandardImageFromData(pictureData));
}
catch (e) {
window.console.log(e);
}
}
}


/**
* Manage resize event calling the parseDOM function
* only if they've passed 100 milliseconds between a resize event and another
* to avoid the script to slower the browser on animated resize or browser edge dragging
*/

if (window.addEventListener) {
window.addEventListener('resize', function() {
clearTimeout(timerId);
timerId = setTimeout(function() {
window.picturePolyfill();
}, 100);
});
window.addEventListener( "DOMContentLoaded", function(){
window.picturePolyfill();
window.removeEventListener( "load", window.picturePolyfill, false );
});
}


/**
* Expose the function to the global environment, if browser is supported, else empty function
* @type {Function}
*/

window.picturePolyfill = (!document.querySelectorAll) ? function(){} : parseDOM;

}());

</script>

<!-- Picturefill markup -->
<span data-picturefill data-alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia">
Expand All @@ -250,5 +24,8 @@
<noscript><img src="http://demo.api.pixtulate.com/demo/large-2.jpg?w=960" alt="A beautiful responsive image"/></noscript>
</span>

<script src="js/picturefill.js"></script>
<script src="../picturePolyfill.js"></script>

</body>
</html>

0 comments on commit 5b1e805

Please sign in to comment.