jquery.svgicons.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*
  2. * SVG Icon Loader 2.0
  3. *
  4. * jQuery Plugin for loading SVG icons from a single file
  5. *
  6. * Copyright (c) 2009 Alexis Deveria
  7. * http://a.deveria.com
  8. *
  9. * MIT License
  10. How to use:
  11. 1. Create the SVG master file that includes all icons:
  12. The master SVG icon-containing file is an SVG file that contains
  13. <g> elements. Each <g> element should contain the markup of an SVG
  14. icon. The <g> element has an ID that should
  15. correspond with the ID of the HTML element used on the page that should contain
  16. or optionally be replaced by the icon. Additionally, one empty element should be
  17. added at the end with id "svg_eof".
  18. 2. Optionally create fallback raster images for each SVG icon.
  19. 3. Include the jQuery and the SVG Icon Loader scripts on your page.
  20. 4. Run $.svgIcons() when the document is ready:
  21. $.svgIcons( file [string], options [object literal]);
  22. File is the location of a local SVG or SVGz file.
  23. All options are optional and can include:
  24. - 'w (number)': The icon widths
  25. - 'h (number)': The icon heights
  26. - 'fallback (object literal)': List of raster images with each
  27. key being the SVG icon ID to replace, and the value the image file name.
  28. - 'fallback_path (string)': The path to use for all images
  29. listed under "fallback"
  30. - 'replace (boolean)': If set to true, HTML elements will be replaced by,
  31. rather than include the SVG icon.
  32. - 'placement (object literal)': List with selectors for keys and SVG icon ids
  33. as values. This provides a custom method of adding icons.
  34. - 'resize (object literal)': List with selectors for keys and numbers
  35. as values. This allows an easy way to resize specific icons.
  36. - 'callback (function)': A function to call when all icons have been loaded.
  37. Includes an object literal as its argument with as keys all icon IDs and the
  38. icon as a jQuery object as its value.
  39. - 'id_match (boolean)': Automatically attempt to match SVG icon ids with
  40. corresponding HTML id (default: true)
  41. - 'no_img (boolean)': Prevent attempting to convert the icon into an <img>
  42. element (may be faster, help for browser consistency)
  43. - 'svgz (boolean)': Indicate that the file is an SVGZ file, and thus not to
  44. parse as XML. SVGZ files add compression benefits, but getting data from
  45. them fails in Firefox 2 and older.
  46. 5. To access an icon at a later point without using the callback, use this:
  47. $.getSvgIcon(id (string));
  48. This will return the icon (as jQuery object) with a given ID.
  49. 6. To resize icons at a later point without using the callback, use this:
  50. $.resizeSvgIcons(resizeOptions) (use the same way as the "resize" parameter)
  51. Example usage #1:
  52. $(function() {
  53. $.svgIcons('my_icon_set.svg'); // The SVG file that contains all icons
  54. // No options have been set, so all icons will automatically be inserted
  55. // into HTML elements that match the same IDs.
  56. });
  57. Example usage #2:
  58. $(function() {
  59. $.svgIcons('my_icon_set.svg', { // The SVG file that contains all icons
  60. callback: function(icons) { // Custom callback function that sets click
  61. // events for each icon
  62. $.each(icons, function(id, icon) {
  63. icon.click(function() {
  64. alert('You clicked on the icon with id ' + id);
  65. });
  66. });
  67. }
  68. }); //The SVG file that contains all icons
  69. });
  70. Example usage #3:
  71. $(function() {
  72. $.svgIcons('my_icon_set.svgz', { // The SVGZ file that contains all icons
  73. w: 32, // All icons will be 32px wide
  74. h: 32, // All icons will be 32px high
  75. fallback_path: 'icons/', // All fallback files can be found here
  76. fallback: {
  77. '#open_icon': 'open.png', // The "open.png" will be appended to the
  78. // HTML element with ID "open_icon"
  79. '#close_icon': 'close.png',
  80. '#save_icon': 'save.png'
  81. },
  82. placement: {'.open_icon','open'}, // The "open" icon will be added
  83. // to all elements with class "open_icon"
  84. resize: function() {
  85. '#save_icon .svg_icon': 64 // The "save" icon will be resized to 64 x 64px
  86. },
  87. callback: function(icons) { // Sets background color for "close" icon
  88. icons['close'].css('background','red');
  89. },
  90. svgz: true // Indicates that an SVGZ file is being used
  91. })
  92. });
  93. */
  94. (function($) {
  95. var svg_icons = {}, fixIDs;
  96. $.svgIcons = function(file, opts) {
  97. var svgns = "http://www.w3.org/2000/svg",
  98. xlinkns = "http://www.w3.org/1999/xlink",
  99. icon_w = opts.w?opts.w : 24,
  100. icon_h = opts.h?opts.h : 24,
  101. elems, svgdoc, testImg,
  102. icons_made = false, data_loaded = false, load_attempts = 0,
  103. ua = navigator.userAgent, isOpera = !!window.opera, isSafari = (ua.indexOf('Safari/') > -1 && ua.indexOf('Chrome/')==-1),
  104. data_pre = 'data:image/svg+xml;charset=utf-8;base64,';
  105. if(opts.svgz) {
  106. var data_el = $('<object data="' + file + '" type=image/svg+xml>').appendTo('body').hide();
  107. try {
  108. svgdoc = data_el[0].contentDocument;
  109. data_el.load(getIcons);
  110. getIcons(0, true); // Opera will not run "load" event if file is already cached
  111. } catch(err1) {
  112. useFallback();
  113. }
  114. } else {
  115. var parser = new DOMParser();
  116. $.ajax({
  117. url: file,
  118. dataType: 'string',
  119. success: function(data) {
  120. if(!data) {
  121. $(useFallback);
  122. return;
  123. }
  124. svgdoc = parser.parseFromString(data, "text/xml");
  125. $(function() {
  126. getIcons('ajax');
  127. });
  128. },
  129. error: function(err) {
  130. // TODO: Fix Opera widget icon bug
  131. if(window.opera) {
  132. $(function() {
  133. useFallback();
  134. });
  135. } else {
  136. if(err.responseText) {
  137. svgdoc = parser.parseFromString(err.responseText, "text/xml");
  138. if(!svgdoc.childNodes.length) {
  139. $(useFallback);
  140. }
  141. $(function() {
  142. getIcons('ajax');
  143. });
  144. } else {
  145. $(useFallback);
  146. }
  147. }
  148. }
  149. });
  150. }
  151. function getIcons(evt, no_wait) {
  152. if(evt !== 'ajax') {
  153. if(data_loaded) return;
  154. // Webkit sometimes says svgdoc is undefined, other times
  155. // it fails to load all nodes. Thus we must make sure the "eof"
  156. // element is loaded.
  157. svgdoc = data_el[0].contentDocument; // Needed again for Webkit
  158. var isReady = (svgdoc && svgdoc.getElementById('svg_eof'));
  159. if(!isReady && !(no_wait && isReady)) {
  160. load_attempts++;
  161. if(load_attempts < 50) {
  162. setTimeout(getIcons, 20);
  163. } else {
  164. useFallback();
  165. data_loaded = true;
  166. }
  167. return;
  168. }
  169. data_loaded = true;
  170. }
  171. elems = $(svgdoc.firstChild).children(); //.getElementsByTagName('foreignContent');
  172. if(!opts.no_img) {
  173. var testSrc = data_pre + 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D';
  174. testImg = $(new Image()).attr({
  175. src: testSrc,
  176. width: 0,
  177. height: 0
  178. }).appendTo('body')
  179. .load(function () {
  180. // Safari 4 crashes, Opera and Chrome don't
  181. makeIcons(true);
  182. }).error(function () {
  183. makeIcons();
  184. });
  185. } else {
  186. setTimeout(function() {
  187. if(!icons_made) makeIcons();
  188. },500);
  189. }
  190. }
  191. var setIcon = function(target, icon, id, setID) {
  192. if(isOpera) icon.css('visibility','hidden');
  193. if(opts.replace) {
  194. if(setID) icon.attr('id',id);
  195. var cl = target.attr('class');
  196. if(cl) icon.attr('class','svg_icon '+cl);
  197. target.replaceWith(icon);
  198. } else {
  199. target.append(icon);
  200. }
  201. if(isOpera) {
  202. setTimeout(function() {
  203. icon.removeAttr('style');
  204. },1);
  205. }
  206. };
  207. var addIcon = function(icon, id) {
  208. if(opts.id_match === undefined || opts.id_match !== false) {
  209. setIcon(holder, icon, id, true);
  210. }
  211. svg_icons[id] = icon;
  212. };
  213. function makeIcons(toImage, fallback) {
  214. if(icons_made) return;
  215. if(opts.no_img) toImage = false;
  216. var holder, temp_holder;
  217. if(toImage) {
  218. temp_holder = $(document.createElement('div'));
  219. temp_holder.hide().appendTo('body');
  220. }
  221. if(fallback) {
  222. var path = opts.fallback_path?opts.fallback_path:'';
  223. $.each(fallback, function(id, imgsrc) {
  224. holder = $('#' + id);
  225. var icon = $(new Image())
  226. .attr({
  227. 'class':'svg_icon',
  228. src: path + imgsrc,
  229. 'width': icon_w,
  230. 'height': icon_h,
  231. 'alt': 'icon'
  232. });
  233. addIcon(icon, id);
  234. });
  235. } else {
  236. var len = elems.length;
  237. for(var i = 0; i < len; i++) {
  238. var elem = elems[i];
  239. var id = elem.id;
  240. if(id === 'svg_eof') break;
  241. holder = $('#' + id);
  242. var svg = elem.getElementsByTagNameNS(svgns, 'svg')[0];
  243. var svgroot = document.createElementNS(svgns, "svg");
  244. // Per http://www.w3.org/TR/xml-names11/#defaulting, the namespace for
  245. // attributes should have no value.
  246. svgroot.setAttributeNS(null, 'viewBox', [0,0,icon_w,icon_h].join(' '));
  247. // Make flexible by converting width/height to viewBox
  248. var w = svg.getAttribute('width');
  249. var h = svg.getAttribute('height');
  250. svg.removeAttribute('width');
  251. svg.removeAttribute('height');
  252. var vb = svg.getAttribute('viewBox');
  253. if(!vb) {
  254. svg.setAttribute('viewBox', [0,0,w,h].join(' '));
  255. }
  256. // Not using jQuery to be a bit faster
  257. svgroot.setAttribute('xmlns', svgns);
  258. svgroot.setAttribute('width', icon_w);
  259. svgroot.setAttribute('height', icon_h);
  260. svgroot.setAttribute("xmlns:xlink", xlinkns);
  261. svgroot.setAttribute("class", 'svg_icon');
  262. // Without cloning, Firefox will make another GET request.
  263. // With cloning, causes issue in Opera/Win/Non-EN
  264. if(!isOpera) svg = svg.cloneNode(true);
  265. svgroot.appendChild(svg);
  266. var icon;
  267. if(toImage) {
  268. temp_holder.empty().append(svgroot);
  269. var str = data_pre + encode64(unescape(encodeURIComponent(new XMLSerializer().serializeToString(svgroot))));
  270. icon = $(new Image())
  271. .attr({'class':'svg_icon', src:str});
  272. } else {
  273. icon = fixIDs($(svgroot), i);
  274. }
  275. addIcon(icon, id);
  276. }
  277. }
  278. if(opts.placement) {
  279. $.each(opts.placement, function(sel, id) {
  280. if(!svg_icons[id]) return;
  281. $(sel).each(function(i) {
  282. var copy = svg_icons[id].clone();
  283. if(i > 0 && !toImage) copy = fixIDs(copy, i, true);
  284. setIcon($(this), copy, id);
  285. });
  286. });
  287. }
  288. if(!fallback) {
  289. if(toImage) temp_holder.remove();
  290. if(data_el) data_el.remove();
  291. if(testImg) testImg.remove();
  292. }
  293. if(opts.resize) $.resizeSvgIcons(opts.resize);
  294. icons_made = true;
  295. if(opts.callback) opts.callback(svg_icons);
  296. }
  297. fixIDs = function(svg_el, svg_num, force) {
  298. var defs = svg_el.find('defs');
  299. if(!defs.length) return svg_el;
  300. var id_elems;
  301. if(isOpera) {
  302. id_elems = defs.find('*').filter(function() {
  303. return !!this.id;
  304. });
  305. } else {
  306. id_elems = defs.find('[id]');
  307. }
  308. var all_elems = svg_el[0].getElementsByTagName('*'), len = all_elems.length;
  309. id_elems.each(function(i) {
  310. var id = this.id;
  311. var no_dupes = ($(svgdoc).find('#' + id).length <= 1);
  312. if(isOpera) no_dupes = false; // Opera didn't clone svg_el, so not reliable
  313. // if(!force && no_dupes) return;
  314. var new_id = 'x' + id + svg_num + i;
  315. this.id = new_id;
  316. var old_val = 'url(#' + id + ')';
  317. var new_val = 'url(#' + new_id + ')';
  318. // Selector method, possibly faster but fails in Opera / jQuery 1.4.3
  319. // svg_el.find('[fill="url(#' + id + ')"]').each(function() {
  320. // this.setAttribute('fill', 'url(#' + new_id + ')');
  321. // }).end().find('[stroke="url(#' + id + ')"]').each(function() {
  322. // this.setAttribute('stroke', 'url(#' + new_id + ')');
  323. // }).end().find('use').each(function() {
  324. // if(this.getAttribute('xlink:href') == '#' + id) {
  325. // this.setAttributeNS(xlinkns,'href','#' + new_id);
  326. // }
  327. // }).end().find('[filter="url(#' + id + ')"]').each(function() {
  328. // this.setAttribute('filter', 'url(#' + new_id + ')');
  329. // });
  330. for(i = 0; i < len; i++) {
  331. var elem = all_elems[i];
  332. if(elem.getAttribute('fill') === old_val) {
  333. elem.setAttribute('fill', new_val);
  334. }
  335. if(elem.getAttribute('stroke') === old_val) {
  336. elem.setAttribute('stroke', new_val);
  337. }
  338. if(elem.getAttribute('filter') === old_val) {
  339. elem.setAttribute('filter', new_val);
  340. }
  341. }
  342. });
  343. return svg_el;
  344. };
  345. function useFallback() {
  346. if(file.indexOf('.svgz') != -1) {
  347. var reg_file = file.replace('.svgz','.svg');
  348. if(window.console) {
  349. console.log('.svgz failed, trying with .svg');
  350. }
  351. $.svgIcons(reg_file, opts);
  352. } else if(opts.fallback) {
  353. makeIcons(false, opts.fallback);
  354. }
  355. }
  356. function encode64(input) {
  357. // base64 strings are 4/3 larger than the original string
  358. if(window.btoa) return window.btoa(input);
  359. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  360. var output = new Array( Math.floor( (input.length + 2) / 3 ) * 4 );
  361. var chr1, chr2, chr3;
  362. var enc1, enc2, enc3, enc4;
  363. var i = 0, p = 0;
  364. do {
  365. chr1 = input.charCodeAt(i++);
  366. chr2 = input.charCodeAt(i++);
  367. chr3 = input.charCodeAt(i++);
  368. enc1 = chr1 >> 2;
  369. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  370. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  371. enc4 = chr3 & 63;
  372. if (isNaN(chr2)) {
  373. enc3 = enc4 = 64;
  374. } else if (isNaN(chr3)) {
  375. enc4 = 64;
  376. }
  377. output[p++] = _keyStr.charAt(enc1);
  378. output[p++] = _keyStr.charAt(enc2);
  379. output[p++] = _keyStr.charAt(enc3);
  380. output[p++] = _keyStr.charAt(enc4);
  381. } while (i < input.length);
  382. return output.join('');
  383. }
  384. };
  385. $.getSvgIcon = function(id, uniqueClone) {
  386. var icon = svg_icons[id];
  387. if(uniqueClone && icon) {
  388. icon = fixIDs(icon, 0, true).clone(true);
  389. }
  390. return icon;
  391. };
  392. $.resizeSvgIcons = function(obj) {
  393. // FF2 and older don't detect .svg_icon, so we change it detect svg elems instead
  394. var change_sel = !$('.svg_icon:first').length;
  395. $.each(obj, function(sel, size) {
  396. var arr = $.isArray(size);
  397. var w = arr?size[0]:size,
  398. h = arr?size[1]:size;
  399. if(change_sel) {
  400. sel = sel.replace(/\.svg_icon/g,'svg');
  401. }
  402. $(sel).each(function() {
  403. this.setAttribute('width', w);
  404. this.setAttribute('height', h);
  405. if(window.opera && window.widget) {
  406. this.parentNode.style.width = w + 'px';
  407. this.parentNode.style.height = h + 'px';
  408. }
  409. });
  410. });
  411. };
  412. })(jQuery);