holder.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. Holder - 1.9 - client side image placeholders
  3. (c) 2012-2013 Ivan Malopinsky / http://imsky.co
  4. Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
  5. Commercial use requires attribution.
  6. */
  7. var Holder = Holder || {};
  8. (function (app, win) {
  9. var preempted = false,
  10. fallback = false,
  11. canvas = document.createElement('canvas');
  12. //getElementsByClassName polyfill
  13. 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})
  14. //getComputedStyle polyfill
  15. window.getComputedStyle||(window.getComputedStyle=function(e,t){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})
  16. //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications
  17. 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)}};
  18. //https://gist.github.com/991057 by Jed Schmidt with modifications
  19. function selector(a){
  20. a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]);
  21. var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret;
  22. }
  23. //shallow object property extend
  24. 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}
  25. //hasOwnProperty polyfill
  26. if (!Object.prototype.hasOwnProperty)
  27. Object.prototype.hasOwnProperty = function(prop) {
  28. var proto = this.__proto__ || this.constructor.prototype;
  29. return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
  30. }
  31. function text_size(width, height, template) {
  32. var dimension_arr = [height, width].sort();
  33. var maxFactor = Math.round(dimension_arr[1] / 16),
  34. minFactor = Math.round(dimension_arr[0] / 16);
  35. var text_height = Math.max(template.size, maxFactor);
  36. return {
  37. height: text_height
  38. }
  39. }
  40. function draw(ctx, dimensions, template, ratio) {
  41. var ts = text_size(dimensions.width, dimensions.height, template);
  42. var text_height = ts.height;
  43. var width = dimensions.width * ratio, height = dimensions.height * ratio;
  44. var font = template.font ? template.font : "sans-serif";
  45. canvas.width = width;
  46. canvas.height = height;
  47. ctx.textAlign = "center";
  48. ctx.textBaseline = "middle";
  49. ctx.fillStyle = template.background;
  50. ctx.fillRect(0, 0, width, height);
  51. ctx.fillStyle = template.foreground;
  52. ctx.font = "bold " + text_height + "px "+font;
  53. var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height);
  54. if (ctx.measureText(text).width / width > 1) {
  55. text_height = template.size / (ctx.measureText(text).width / width);
  56. }
  57. //Resetting font size if necessary
  58. ctx.font = "bold " + (text_height * ratio) + "px "+font;
  59. ctx.fillText(text, (width / 2), (height / 2), width);
  60. return canvas.toDataURL("image/png");
  61. }
  62. function render(mode, el, holder, src) {
  63. var dimensions = holder.dimensions,
  64. theme = holder.theme,
  65. text = holder.text ? decodeURIComponent(holder.text) : holder.text;
  66. var dimensions_caption = dimensions.width + "x" + dimensions.height;
  67. theme = (text ? extend(theme, { text: text }) : theme);
  68. theme = (holder.font ? extend(theme, {font: holder.font}) : theme);
  69. var ratio = 1;
  70. if(window.devicePixelRatio && window.devicePixelRatio > 1){
  71. ratio = window.devicePixelRatio;
  72. }
  73. if (mode == "image") {
  74. el.setAttribute("data-src", src);
  75. el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption);
  76. if(fallback || !holder.auto){
  77. el.style.width = dimensions.width + "px";
  78. el.style.height = dimensions.height + "px";
  79. }
  80. if (fallback) {
  81. el.style.backgroundColor = theme.background;
  82. }
  83. else{
  84. el.setAttribute("src", draw(ctx, dimensions, theme, ratio));
  85. }
  86. } else {
  87. if (!fallback) {
  88. el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")";
  89. el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px";
  90. }
  91. }
  92. };
  93. function fluid(el, holder, src) {
  94. var dimensions = holder.dimensions,
  95. theme = holder.theme,
  96. text = holder.text;
  97. var dimensions_caption = dimensions.width + "x" + dimensions.height;
  98. theme = (text ? extend(theme, {
  99. text: text
  100. }) : theme);
  101. var fluid = document.createElement("div");
  102. fluid.style.backgroundColor = theme.background;
  103. fluid.style.color = theme.foreground;
  104. fluid.className = el.className + " holderjs-fluid";
  105. fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px");
  106. fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px");
  107. fluid.id = el.id;
  108. el.style.width=0;
  109. el.style.height=0;
  110. if (theme.text) {
  111. fluid.appendChild(document.createTextNode(theme.text))
  112. } else {
  113. fluid.appendChild(document.createTextNode(dimensions_caption))
  114. fluid_images.push(fluid);
  115. setTimeout(fluid_update, 0);
  116. }
  117. el.parentNode.insertBefore(fluid, el.nextSibling)
  118. if(window.jQuery){
  119. jQuery(function($){
  120. $(el).on("load", function(){
  121. el.style.width = fluid.style.width;
  122. el.style.height = fluid.style.height;
  123. $(el).show();
  124. $(fluid).remove();
  125. });
  126. })
  127. }
  128. }
  129. function fluid_update() {
  130. for (i in fluid_images) {
  131. if(!fluid_images.hasOwnProperty(i)) continue;
  132. var el = fluid_images[i],
  133. label = el.firstChild;
  134. el.style.lineHeight = el.offsetHeight+"px";
  135. label.data = el.offsetWidth + "x" + el.offsetHeight;
  136. }
  137. }
  138. function parse_flags(flags, options) {
  139. var ret = {
  140. theme: settings.themes.gray
  141. }, render = false;
  142. for (sl = flags.length, j = 0; j < sl; j++) {
  143. var flag = flags[j];
  144. if (app.flags.dimensions.match(flag)) {
  145. render = true;
  146. ret.dimensions = app.flags.dimensions.output(flag);
  147. } else if (app.flags.fluid.match(flag)) {
  148. render = true;
  149. ret.dimensions = app.flags.fluid.output(flag);
  150. ret.fluid = true;
  151. } else if (app.flags.colors.match(flag)) {
  152. ret.theme = app.flags.colors.output(flag);
  153. } else if (options.themes[flag]) {
  154. //If a theme is specified, it will override custom colors
  155. ret.theme = options.themes[flag];
  156. } else if (app.flags.text.match(flag)) {
  157. ret.text = app.flags.text.output(flag);
  158. } else if(app.flags.font.match(flag)){
  159. ret.font = app.flags.font.output(flag);
  160. }
  161. else if(app.flags.auto.match(flag)){
  162. ret.auto = true;
  163. }
  164. }
  165. return render ? ret : false;
  166. };
  167. if (!canvas.getContext) {
  168. fallback = true;
  169. } else {
  170. if (canvas.toDataURL("image/png")
  171. .indexOf("data:image/png") < 0) {
  172. //Android doesn't support data URI
  173. fallback = true;
  174. } else {
  175. var ctx = canvas.getContext("2d");
  176. }
  177. }
  178. var fluid_images = [];
  179. var settings = {
  180. domain: "holder.js",
  181. images: "img",
  182. bgnodes: ".holderjs",
  183. themes: {
  184. "gray": {
  185. background: "#eee",
  186. foreground: "#aaa",
  187. size: 12
  188. },
  189. "social": {
  190. background: "#3a5a97",
  191. foreground: "#fff",
  192. size: 12
  193. },
  194. "industrial": {
  195. background: "#434A52",
  196. foreground: "#C2F200",
  197. size: 12
  198. }
  199. },
  200. stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;margin:0}"
  201. };
  202. app.flags = {
  203. dimensions: {
  204. regex: /^(\d+)x(\d+)$/,
  205. output: function (val) {
  206. var exec = this.regex.exec(val);
  207. return {
  208. width: +exec[1],
  209. height: +exec[2]
  210. }
  211. }
  212. },
  213. fluid: {
  214. regex: /^([0-9%]+)x([0-9%]+)$/,
  215. output: function (val) {
  216. var exec = this.regex.exec(val);
  217. return {
  218. width: exec[1],
  219. height: exec[2]
  220. }
  221. }
  222. },
  223. colors: {
  224. regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i,
  225. output: function (val) {
  226. var exec = this.regex.exec(val);
  227. return {
  228. size: settings.themes.gray.size,
  229. foreground: "#" + exec[2],
  230. background: "#" + exec[1]
  231. }
  232. }
  233. },
  234. text: {
  235. regex: /text\:(.*)/,
  236. output: function (val) {
  237. return this.regex.exec(val)[1];
  238. }
  239. },
  240. font: {
  241. regex: /font\:(.*)/,
  242. output: function(val){
  243. return this.regex.exec(val)[1];
  244. }
  245. },
  246. auto: {
  247. regex: /^auto$/
  248. }
  249. }
  250. for (var flag in app.flags) {
  251. if(!app.flags.hasOwnProperty(flag)) continue;
  252. app.flags[flag].match = function (val) {
  253. return val.match(this.regex)
  254. }
  255. }
  256. app.add_theme = function (name, theme) {
  257. name != null && theme != null && (settings.themes[name] = theme);
  258. return app;
  259. };
  260. app.add_image = function (src, el) {
  261. var node = selector(el);
  262. if (node.length) {
  263. for (var i = 0, l = node.length; i < l; i++) {
  264. var img = document.createElement("img")
  265. img.setAttribute("data-src", src);
  266. node[i].appendChild(img);
  267. }
  268. }
  269. return app;
  270. };
  271. app.run = function (o) {
  272. var options = extend(settings, o), images = [];
  273. if(options.images instanceof window.NodeList){
  274. imageNodes = options.images;
  275. }
  276. else if(options.images instanceof window.Node){
  277. imageNodes = [options.images];
  278. }
  279. else{
  280. imageNodes = selector(options.images);
  281. }
  282. if(options.elements instanceof window.NodeList){
  283. bgnodes = options.bgnodes;
  284. }
  285. else if(options.bgnodes instanceof window.Node){
  286. bgnodes = [options.bgnodes];
  287. }
  288. else{
  289. bgnodes = selector(options.bgnodes);
  290. }
  291. preempted = true;
  292. for (i = 0, l = imageNodes.length; i < l; i++) images.push(imageNodes[i]);
  293. var holdercss = document.getElementById("holderjs-style");
  294. if(!holdercss){
  295. holdercss = document.createElement("style");
  296. holdercss.setAttribute("id", "holderjs-style");
  297. holdercss.type = "text/css";
  298. document.getElementsByTagName("head")[0].appendChild(holdercss);
  299. }
  300. if(holdercss.styleSheet){
  301. holdercss.styleSheet += options.stylesheet;
  302. }
  303. else{
  304. holdercss.textContent+= options.stylesheet;
  305. }
  306. var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)");
  307. for (var l = bgnodes.length, i = 0; i < l; i++) {
  308. var src = window.getComputedStyle(bgnodes[i], null)
  309. .getPropertyValue("background-image");
  310. var flags = src.match(cssregex);
  311. if (flags) {
  312. var holder = parse_flags(flags[1].split("/"), options);
  313. if (holder) {
  314. render("background", bgnodes[i], holder, src);
  315. }
  316. }
  317. }
  318. for (var l = images.length, i = 0; i < l; i++) {
  319. var src = images[i].getAttribute("src") || images[i].getAttribute("data-src");
  320. if (src != null && src.indexOf(options.domain) >= 0) {
  321. var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1)
  322. .split("/"), options);
  323. if (holder) {
  324. if (holder.fluid) {
  325. fluid(images[i], holder, src);
  326. } else {
  327. render("image", images[i], holder, src);
  328. }
  329. }
  330. }
  331. }
  332. return app;
  333. };
  334. contentLoaded(win, function () {
  335. if (window.addEventListener) {
  336. window.addEventListener("resize", fluid_update, false);
  337. window.addEventListener("orientationchange", fluid_update, false);
  338. } else {
  339. window.attachEvent("onresize", fluid_update)
  340. }
  341. preempted || app.run();
  342. });
  343. if ( typeof define === "function" && define.amd ) {
  344. define( "Holder", [], function () { return app; } );
  345. }
  346. })(Holder, window);