image.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /** @license
  2. * RequireJS Image Plugin
  3. * Author: Miller Medeiros
  4. * Version: 0.2.2 (2013/02/08)
  5. * Released under the MIT license
  6. */
  7. define(function(){
  8. var CACHE_BUST_QUERY_PARAM = 'bust',
  9. CACHE_BUST_FLAG = '!bust',
  10. RELATIVE_FLAG = '!rel';
  11. function noop(){}
  12. function cacheBust(url){
  13. url = url.replace(CACHE_BUST_FLAG, '');
  14. url += (url.indexOf('?') < 0)? '?' : '&';
  15. return url + CACHE_BUST_QUERY_PARAM +'='+ Math.round(2147483647 * Math.random());
  16. }
  17. return {
  18. load : function(name, req, onLoad, config){
  19. var img;
  20. if(config.isBuild){
  21. onLoad(null); //avoid errors on the optimizer since it can't inline image files
  22. }else{
  23. img = new Image();
  24. img.onerror = function (err) {
  25. onLoad.error(err);
  26. };
  27. img.onload = function(evt){
  28. onLoad(img);
  29. try {
  30. delete img.onload; //release memory - suggested by John Hann
  31. } catch(err) {
  32. img.onload = noop; // IE7 :(
  33. }
  34. };
  35. if (name.indexOf(RELATIVE_FLAG) !== -1) {
  36. //load image relative to module path / baseUrl
  37. img.src = req.toUrl( name.replace(RELATIVE_FLAG, '') );
  38. } else {
  39. img.src = name;
  40. }
  41. }
  42. },
  43. normalize : function (name, normalize) {
  44. //used normalize to avoid caching references to a "cache busted" request
  45. return (name.indexOf(CACHE_BUST_FLAG) === -1)? name : cacheBust(name);
  46. }
  47. };
  48. });