How to determine if jQuery is running on a page (even if jQuery is /after/ the detection script)

后端 未结 3 571
再見小時候
再見小時候 2021-02-08 19:04

I\'m working on a do-dad that can be embedded in a page like a youtube video. The particular effect I want needs jQuery to work.

I want to load jQuery on the condition t

3条回答
  •  再見小時候
    2021-02-08 19:54

    Given your constraints, I see only two options:

    1. Use window.load event:

      (function() {
          if (window.addEventListener) {
              // Standard
              window.addEventListener('load', jQueryCheck, false);
          }
          else if (window.attachEvent) {
              // Microsoft
              window.attachEvent('onload', jQueryCheck);
          }
          function jQueryCheck() {
              if (typeof jQuery === "undefined") {
                  // No one's loaded it; either load it or do without
              }
          }
      })();
      

      window.load happens very late in the loading cycle, though, after all images are and such loaded.

    2. Use a timeout. The good news is that the timeout can probably be quite short.

      (function() {
          var counter = 0;
      
          doDetect();
          function doDetect() {
              if (typeof jQuery !== "undefined") {
                  // ...jQuery has been loaded
              }
              else if (++counter < 5) { // 5 or whatever
                  setTimeout(doDetect, 10);
              }
              else {
                  // Time out (and either load it or don't)
              }
          }
      })();
      

      You'll have to tune to decide the best values for the counter and the interval. But if jQuery isn't loaded even on the first or second loop, my guess (untested) is that it isn't going to be loaded...unless someone else is doing what you're doing. :-)

提交回复
热议问题