Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. A17.Helpers.execute_script_tags = function(container) {
  2. var loaded = false;
  3. var progress = 0;
  4. var $container = $(container);
  5.  
  6. var current_script = null;
  7. var head = document.getElementsByTagName('head')[0] || document.body;
  8. var new_scripts_to_load = $('script[src]', $container);
  9. var new_scripts_to_eval = $('script:not([src])', $container);
  10. var existing_scripts = $('script[src]', $(head));
  11.  
  12. if(new_scripts_to_load.length) {
  13. if(progress < new_scripts_to_load.length) startLoad(new_scripts_to_load[progress]);
  14. }
  15.  
  16. function startLoad(target) {
  17. loaded = false;
  18.  
  19. var $target = $(target);
  20. var src = target.src;
  21.  
  22. var matchedScripts = existing_scripts.filter(function() {
  23. return target.src === src;
  24. })
  25. if (matchedScripts.length) {
  26. matchedScripts.remove();
  27. }
  28.  
  29. var script = document.createElement('script');
  30. current_script = script;
  31.  
  32. if (typeof($target.attr('type')) !== "undefined") {
  33. script.type = $target.attr('type');
  34. }
  35.  
  36. script.src = $target.attr('src');
  37. script.onload = handleLoad;
  38. script.onreadystatechange = handleReadyStateChange;
  39. script.onerror = handleError;
  40.  
  41. head.appendChild(script);
  42. };
  43.  
  44. function handleLoad() {
  45. if (!loaded) continueLoading();
  46. }
  47.  
  48. function handleReadyStateChange() {
  49. var state;
  50.  
  51. if (!loaded) {
  52. state = current_script.readyState;
  53. if (state === "complete") handleLoad();
  54. }
  55. }
  56. function handleError() {
  57. if (!loaded) continueLoading();
  58. }
  59.  
  60. function continueLoading() {
  61. loaded = true;
  62. progress++;
  63. if(progress < new_scripts_to_load.length) startLoad(new_scripts_to_load[progress]);
  64. else if(new_scripts_to_eval.length) evalScripts();
  65. }
  66.  
  67. function evalScripts() {
  68. new_scripts_to_eval.each(function() {
  69. var target = this;
  70.  
  71. var script = document.createElement('script');
  72. script.text = target.textContent;
  73.  
  74. // Place the scripts in the head instead of the body to avoid errors
  75. // when called from the head in the first place.
  76. head.appendChild(script);
  77.  
  78. // Remove scripts afterwards to avoid unnecessary increased DOM size.
  79. head.removeChild(script);
  80. });
  81. }
  82. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement