jquery.svgicons.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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;
  217. if(toImage) {
  218. var 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. svgroot.setAttributeNS(svgns, 'viewBox', [0,0,icon_w,icon_h].join(' '));
  245. // Make flexible by converting width/height to viewBox
  246. var w = svg.getAttribute('width');
  247. var h = svg.getAttribute('height');
  248. svg.removeAttribute('width');
  249. svg.removeAttribute('height');
  250. var vb = svg.getAttribute('viewBox');
  251. if(!vb) {
  252. svg.setAttribute('viewBox', [0,0,w,h].join(' '));
  253. }
  254. // Not using jQuery to be a bit faster
  255. svgroot.setAttribute('xmlns', svgns);
  256. svgroot.setAttribute('width', icon_w);
  257. svgroot.setAttribute('height', icon_h);
  258. svgroot.setAttribute("xmlns:xlink", xlinkns);
  259. svgroot.setAttribute("class", 'svg_icon');
  260. // Without cloning, Firefox will make another GET request.
  261. // With cloning, causes issue in Opera/Win/Non-EN
  262. if(!isOpera) svg = svg.cloneNode(true);
  263. svgroot.appendChild(svg);
  264. if(toImage) {
  265. // Without cloning, Safari will crash
  266. // With cloning, causes issue in Opera/Win/Non-EN
  267. var svgcontent = isOpera?svgroot:svgroot.cloneNode(true);
  268. temp_holder.empty().append(svgroot);
  269. var str = data_pre + encode64(temp_holder.html());
  270. var icon = $(new Image())
  271. .attr({'class':'svg_icon', src:str});
  272. } else {
  273. var 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. if(isOpera) {
  301. var id_elems = defs.find('*').filter(function() {
  302. return !!this.id;
  303. });
  304. } else {
  305. var id_elems = defs.find('[id]');
  306. }
  307. var all_elems = svg_el[0].getElementsByTagName('*'), len = all_elems.length;
  308. id_elems.each(function(i) {
  309. var id = this.id;
  310. var no_dupes = ($(svgdoc).find('#' + id).length <= 1);
  311. if(isOpera) no_dupes = false; // Opera didn't clone svg_el, so not reliable
  312. // if(!force && no_dupes) return;
  313. var new_id = 'x' + id + svg_num + i;
  314. this.id = new_id;
  315. var old_val = 'url(#' + id + ')';
  316. var new_val = 'url(#' + new_id + ')';
  317. // Selector method, possibly faster but fails in Opera / jQuery 1.4.3
  318. // svg_el.find('[fill="url(#' + id + ')"]').each(function() {
  319. // this.setAttribute('fill', 'url(#' + new_id + ')');
  320. // }).end().find('[stroke="url(#' + id + ')"]').each(function() {
  321. // this.setAttribute('stroke', 'url(#' + new_id + ')');
  322. // }).end().find('use').each(function() {
  323. // if(this.getAttribute('xlink:href') == '#' + id) {
  324. // this.setAttributeNS(xlinkns,'href','#' + new_id);
  325. // }
  326. // }).end().find('[filter="url(#' + id + ')"]').each(function() {
  327. // this.setAttribute('filter', 'url(#' + new_id + ')');
  328. // });
  329. for(var i = 0; i < len; i++) {
  330. var elem = all_elems[i];
  331. if(elem.getAttribute('fill') === old_val) {
  332. elem.setAttribute('fill', new_val);
  333. }
  334. if(elem.getAttribute('stroke') === old_val) {
  335. elem.setAttribute('stroke', new_val);
  336. }
  337. if(elem.getAttribute('filter') === old_val) {
  338. elem.setAttribute('filter', new_val);
  339. }
  340. }
  341. });
  342. return svg_el;
  343. }
  344. function useFallback() {
  345. if(file.indexOf('.svgz') != -1) {
  346. var reg_file = file.replace('.svgz','.svg');
  347. if(window.console) {
  348. console.log('.svgz failed, trying with .svg');
  349. }
  350. $.svgIcons(reg_file, opts);
  351. } else if(opts.fallback) {
  352. makeIcons(false, opts.fallback);
  353. }
  354. }
  355. function encode64(input) {
  356. // base64 strings are 4/3 larger than the original string
  357. if(window.btoa) return window.btoa(input);
  358. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  359. var output = new Array( Math.floor( (input.length + 2) / 3 ) * 4 );
  360. var chr1, chr2, chr3;
  361. var enc1, enc2, enc3, enc4;
  362. var i = 0, p = 0;
  363. do {
  364. chr1 = input.charCodeAt(i++);
  365. chr2 = input.charCodeAt(i++);
  366. chr3 = input.charCodeAt(i++);
  367. enc1 = chr1 >> 2;
  368. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  369. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  370. enc4 = chr3 & 63;
  371. if (isNaN(chr2)) {
  372. enc3 = enc4 = 64;
  373. } else if (isNaN(chr3)) {
  374. enc4 = 64;
  375. }
  376. output[p++] = _keyStr.charAt(enc1);
  377. output[p++] = _keyStr.charAt(enc2);
  378. output[p++] = _keyStr.charAt(enc3);
  379. output[p++] = _keyStr.charAt(enc4);
  380. } while (i < input.length);
  381. return output.join('');
  382. }
  383. }
  384. $.getSvgIcon = function(id, uniqueClone) {
  385. var icon = svg_icons[id];
  386. if(uniqueClone && icon) {
  387. icon = fixIDs(icon, 0, true).clone(true);
  388. }
  389. return icon;
  390. }
  391. $.resizeSvgIcons = function(obj) {
  392. // FF2 and older don't detect .svg_icon, so we change it detect svg elems instead
  393. var change_sel = !$('.svg_icon:first').length;
  394. $.each(obj, function(sel, size) {
  395. var arr = $.isArray(size);
  396. var w = arr?size[0]:size,
  397. h = arr?size[1]:size;
  398. if(change_sel) {
  399. sel = sel.replace(/\.svg_icon/g,'svg');
  400. }
  401. $(sel).each(function() {
  402. this.setAttribute('width', w);
  403. this.setAttribute('height', h);
  404. if(window.opera && window.widget) {
  405. this.parentNode.style.width = w + 'px';
  406. this.parentNode.style.height = h + 'px';
  407. }
  408. });
  409. });
  410. }
  411. })(jQuery);