3 Holder - 2.1 - client side image placeholders
4 (c) 2012-2013 Ivan Malopinsky / http://imsky.co
6 Provided under the MIT License.
7 Commercial use requires attribution.
11 var Holder = Holder || {};
12 (function (app, win) {
14 var preempted = false,
16 canvas = document.createElement('canvas');
18 if (!canvas.getContext) {
21 if (canvas.toDataURL("image/png")
22 .indexOf("data:image/png") < 0) {
23 //Android doesn't support data URI
26 var ctx = canvas.getContext("2d");
33 dpr = window.devicePixelRatio || 1,
34 bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
37 var ratio = dpr / bsr;
39 //getElementsByClassName polyfill
40 document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s})
42 //getComputedStyle polyfill
43 window.getComputedStyle||(window.getComputedStyle=function(e){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this})
45 //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications
46 function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}
48 //https://gist.github.com/991057 by Jed Schmidt with modifications
50 a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]);
51 var ret=[]; b!==null&&(b.length?ret=b:b.length===0?ret=b:ret=[b]); return ret;
54 //shallow object property extend
55 function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c}
57 //hasOwnProperty polyfill
58 if (!Object.prototype.hasOwnProperty)
59 /*jshint -W001, -W103 */
60 Object.prototype.hasOwnProperty = function(prop) {
61 var proto = this.__proto__ || this.constructor.prototype;
62 return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
64 /*jshint +W001, +W103 */
66 function text_size(width, height, template) {
67 height = parseInt(height, 10);
68 width = parseInt(width, 10);
69 var bigSide = Math.max(height, width)
70 var smallSide = Math.min(height, width)
72 var newHeight = Math.min(smallSide * 0.75, 0.75 * bigSide * scale);
74 height: Math.round(Math.max(template.size, newHeight))
78 function draw(ctx, dimensions, template, ratio, literal) {
79 var ts = text_size(dimensions.width, dimensions.height, template);
80 var text_height = ts.height;
81 var width = dimensions.width * ratio,
82 height = dimensions.height * ratio;
83 var font = template.font ? template.font : "sans-serif";
85 canvas.height = height;
86 ctx.textAlign = "center";
87 ctx.textBaseline = "middle";
88 ctx.fillStyle = template.background;
89 ctx.fillRect(0, 0, width, height);
90 ctx.fillStyle = template.foreground;
91 ctx.font = "bold " + text_height + "px " + font;
92 var text = template.text ? template.text : (Math.floor(dimensions.width) + "x" + Math.floor(dimensions.height));
94 text = template.literalText;
96 var text_width = ctx.measureText(text).width;
97 if (text_width / width >= 0.75) {
98 text_height = Math.floor(text_height * 0.75 * (width / text_width));
100 //Resetting font size if necessary
101 ctx.font = "bold " + (text_height * ratio) + "px " + font;
102 ctx.fillText(text, (width / 2), (height / 2), width);
103 return canvas.toDataURL("image/png");
106 function render(mode, el, holder, src) {
107 var dimensions = holder.dimensions,
108 theme = holder.theme,
109 text = holder.text ? decodeURIComponent(holder.text) : holder.text;
110 var dimensions_caption = dimensions.width + "x" + dimensions.height;
111 theme = (text ? extend(theme, {
114 theme = (holder.font ? extend(theme, {
117 el.setAttribute("data-src", src);
118 theme.literalText = dimensions_caption;
119 holder.originalTheme = holder.theme;
120 holder.theme = theme;
122 if (mode == "image") {
123 el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption);
124 if (fallback || !holder.auto) {
125 el.style.width = dimensions.width + "px";
126 el.style.height = dimensions.height + "px";
129 el.style.backgroundColor = theme.background;
131 el.setAttribute("src", draw(ctx, dimensions, theme, ratio));
133 } else if (mode == "background") {
135 el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")";
136 el.style.backgroundSize = dimensions.width + "px " + dimensions.height + "px";
138 } else if (mode == "fluid") {
139 el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption);
140 if (dimensions.height.slice(-1) == "%") {
141 el.style.height = dimensions.height
143 el.style.height = dimensions.height + "px"
145 if (dimensions.width.slice(-1) == "%") {
146 el.style.width = dimensions.width
148 el.style.width = dimensions.width + "px"
150 if (el.style.display == "inline" || el.style.display === "") {
151 el.style.display = "block";
154 el.style.backgroundColor = theme.background;
156 el.holderData = holder;
157 fluid_images.push(el);
163 function fluid_update(element) {
165 if (element.nodeType == null) {
166 images = fluid_images;
170 for (var i in images) {
173 var holder = el.holderData;
174 el.setAttribute("src", draw(ctx, {
175 height: el.clientHeight,
176 width: el.clientWidth
177 }, holder.theme, ratio, !! holder.literal));
182 function parse_flags(flags, options) {
184 theme: settings.themes.gray
187 for (sl = flags.length, j = 0; j < sl; j++) {
189 if (app.flags.dimensions.match(flag)) {
191 ret.dimensions = app.flags.dimensions.output(flag);
192 } else if (app.flags.fluid.match(flag)) {
194 ret.dimensions = app.flags.fluid.output(flag);
196 } else if (app.flags.literal.match(flag)) {
198 } else if (app.flags.colors.match(flag)) {
199 ret.theme = app.flags.colors.output(flag);
200 } else if (options.themes[flag]) {
201 //If a theme is specified, it will override custom colors
202 ret.theme = options.themes[flag];
203 } else if (app.flags.font.match(flag)) {
204 ret.font = app.flags.font.output(flag);
205 } else if (app.flags.auto.match(flag)) {
207 } else if (app.flags.text.match(flag)) {
208 ret.text = app.flags.text.output(flag);
211 return render ? ret : false;
213 var fluid_images = [];
217 bgnodes: ".holderjs",
225 background: "#3a5a97",
230 background: "#434A52",
231 foreground: "#C2F200",
239 regex: /^(\d+)x(\d+)$/,
240 output: function (val) {
241 var exec = this.regex.exec(val);
249 regex: /^([0-9%]+)x([0-9%]+)$/,
250 output: function (val) {
251 var exec = this.regex.exec(val);
259 regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i,
260 output: function (val) {
261 var exec = this.regex.exec(val);
263 size: settings.themes.gray.size,
264 foreground: "#" + exec[2],
265 background: "#" + exec[1]
271 output: function (val) {
272 return this.regex.exec(val)[1];
277 output: function (val) {
278 return this.regex.exec(val)[1];
288 for (var flag in app.flags) {
289 if (!app.flags.hasOwnProperty(flag)) continue;
290 app.flags[flag].match = function (val) {
291 return val.match(this.regex)
294 app.add_theme = function (name, theme) {
295 name != null && theme != null && (settings.themes[name] = theme);
298 app.add_image = function (src, el) {
299 var node = selector(el);
301 for (var i = 0, l = node.length; i < l; i++) {
302 var img = document.createElement("img")
303 img.setAttribute("data-src", src);
304 node[i].appendChild(img);
309 app.run = function (o) {
310 var options = extend(settings, o),
314 if (typeof (options.images) == "string") {
315 imageNodes = selector(options.images);
316 } else if (window.NodeList && options.images instanceof window.NodeList) {
317 imageNodes = options.images;
318 } else if (window.Node && options.images instanceof window.Node) {
319 imageNodes = [options.images];
321 if (typeof (options.bgnodes) == "string") {
322 bgnodes = selector(options.bgnodes);
323 } else if (window.NodeList && options.elements instanceof window.NodeList) {
324 bgnodes = options.bgnodes;
325 } else if (window.Node && options.bgnodes instanceof window.Node) {
326 bgnodes = [options.bgnodes];
329 for (i = 0, l = imageNodes.length; i < l; i++) images.push(imageNodes[i]);
330 var holdercss = document.getElementById("holderjs-style");
332 holdercss = document.createElement("style");
333 holdercss.setAttribute("id", "holderjs-style");
334 holdercss.type = "text/css";
335 document.getElementsByTagName("head")[0].appendChild(holdercss);
337 if (!options.nocss) {
338 if (holdercss.styleSheet) {
339 holdercss.styleSheet.cssText += options.stylesheet;
341 holdercss.appendChild(document.createTextNode(options.stylesheet));
344 var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)");
345 for (var l = bgnodes.length, i = 0; i < l; i++) {
346 var src = window.getComputedStyle(bgnodes[i], null)
347 .getPropertyValue("background-image");
348 var flags = src.match(cssregex);
349 var bgsrc = bgnodes[i].getAttribute("data-background-src");
351 var holder = parse_flags(flags[1].split("/"), options);
353 render("background", bgnodes[i], holder, src);
355 } else if (bgsrc != null) {
356 var holder = parse_flags(bgsrc.substr(bgsrc.lastIndexOf(options.domain) + options.domain.length + 1)
357 .split("/"), options);
359 render("background", bgnodes[i], holder, src);
363 for (l = images.length, i = 0; i < l; i++) {
364 var attr_data_src, attr_src;
365 attr_src = attr_data_src = src = null;
367 attr_src = images[i].getAttribute("src");
368 attr_datasrc = images[i].getAttribute("data-src");
370 if (attr_datasrc == null && !! attr_src && attr_src.indexOf(options.domain) >= 0) {
372 } else if ( !! attr_datasrc && attr_datasrc.indexOf(options.domain) >= 0) {
376 var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1)
377 .split("/"), options);
380 render("fluid", images[i], holder, src)
382 render("image", images[i], holder, src);
389 contentLoaded(win, function () {
390 if (window.addEventListener) {
391 window.addEventListener("resize", fluid_update, false);
392 window.addEventListener("orientationchange", fluid_update, false);
394 window.attachEvent("onresize", fluid_update)
396 preempted || app.run();
398 if (typeof define === "function" && define.amd) {
399 define([], function () {