Posted By

remysharp on 11/14/07


Tagged

javascript textmate blocking external wait


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

heinz1959
vali29
jamesming
wirenaught


waitForScript


 / Published in: JavaScript
 

  1. /**
  2. * Only returns true when the external script has been
  3. * loaded in to the DOM. It uses arguments.callee.caller
  4. * to work out which function is the callback.
  5. *
  6. * @param url {String} URL of external script
  7. * @param obj {String} The name of a function or variable
  8. * within the external script to test for.
  9. * @license: Creative Commons License -
  10. * ShareAlike http://creativecommons.org/licenses/by-sa/3.0/
  11. * @author Remy Sharp / leftlogic.com
  12. */
  13. function waitingForScript(url, obj) {
  14. // doesn't work in Opera
  15. var callback = arguments.callee.caller;
  16. var args = arguments.callee.caller.arguments;
  17. var s, ok, timer, doc = document;
  18.  
  19. // if the object/function doesn't exist and we've not tried to load it
  20. // then pull it in and fire the calling function once complete
  21. if ((typeof window[obj] == 'undefined') && !window['loading' + obj]) {
  22. window['loading' + obj] = true;
  23.  
  24. if (!doc.getElementById('_' + obj)) {
  25. s = doc.createElement('script');
  26. s.src = url;
  27. s.id = '_' + obj;
  28. doc.body.appendChild(s);
  29. }
  30.  
  31. timer = setInterval(function () {
  32. ok = false;
  33. try {
  34. ok = (typeof window[obj] != 'undefined');
  35. } catch (e) {}
  36.  
  37. if (ok) {
  38. clearInterval(timer);
  39. callback.apply(this);
  40. }
  41. }, 10);
  42.  
  43. // we're loading in the script now, so we're currently waiting
  44. return true;
  45. } else if (typeof window[obj] == 'undefined') {
  46. // object not defined yet, so we're still waiting
  47. return true;
  48. } else {
  49. // it's already loaded
  50. return false;
  51. }
  52. }

Report this snippet  

You need to login to post a comment.