Safe Script Load


/ Published in: JavaScript
Save to your folder(s)

Safely loads a javascript file asynchronously

Example:

(function() {
__safeLoadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", function() {
alert(jQuery);
});
})();


Copy this code and paste it in your HTML
  1. window.__safeLoadScript = function(src, callback) {
  2.  
  3. function addEvent(obj, type, fn) {
  4. if (obj.attachEvent) {
  5. obj['e' + type + fn] = fn;
  6. obj[type + fn] = function() { obj['e' + type + fn](window.event); }
  7. obj.attachEvent('on' + type, obj[type + fn]);
  8. } else
  9. obj.addEventListener(type, fn, false);
  10. }
  11.  
  12. function async_load(src, callback) {
  13. var s = document.createElement('script');
  14. s.type = 'text/javascript';
  15. s.async = true;
  16. var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
  17. s.src = protocol + src;
  18. var x = document.getElementsByTagName('script')[0];
  19. x.parentNode.insertBefore(s, x);
  20. s.onload = s.onreadystatechange = function() {
  21. if(callback && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
  22. callback();
  23. }
  24. };
  25. }
  26.  
  27. addEvent(window, "load", function() {
  28. async_load(src, callback);
  29. });
  30. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.