map-lazy-load.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @ngdoc directive
  3. * @name lazy-load
  4. * @requires Attr2Options
  5. * @description
  6. * Requires: Delay the initialization of directive until required .js loads
  7. * Restrict To: Attribute
  8. *
  9. * @param {String} lazy-load
  10. script source file location
  11. * example:
  12. * 'http://maps.googlecom/maps/api/js'
  13. * @example
  14. * Example:
  15. *
  16. * <div lazy-load="http://maps.google.com/maps/api/js">
  17. * <map center="Brampton" zoom="10">
  18. * <marker position="Brampton"></marker>
  19. * </map>
  20. * </div>
  21. */
  22. /*jshint -W089*/
  23. ngMap.directive('mapLazyLoad', ['$compile', '$timeout', function($compile, $timeout) {
  24. 'use strict';
  25. var directiveDefinitionObject = {
  26. compile: function(tElement, tAttrs) {
  27. (!tAttrs.mapLazyLoad) && console.error('requires src with map-lazy-load');
  28. var savedHtml = tElement.html(), src = tAttrs.mapLazyLoad;
  29. /**
  30. * if already loaded, stop processing it
  31. */
  32. if (document.querySelector('script[src="'+src+'"]')) {
  33. return false;
  34. }
  35. tElement.html(''); // will compile again after script is loaded
  36. return {
  37. pre: function(scope, element, attrs) {
  38. window.lazyLoadCallback = function() {
  39. console.log('script loaded,' + src);
  40. $timeout(function() { /* give some time to load */
  41. element.html(savedHtml);
  42. $compile(element.contents())(scope);
  43. }, 100);
  44. };
  45. var scriptEl = document.createElement('script');
  46. scriptEl.src = src + '?callback=lazyLoadCallback';
  47. document.body.appendChild(scriptEl);
  48. }
  49. };
  50. }
  51. };
  52. return directiveDefinitionObject;
  53. }]);