Javascript includes not loading for later in the page

前端 未结 7 2667
我寻月下人不归
我寻月下人不归 2021-02-20 08:42

We have a Rails application where we are including our application dependencies in the html head within application.js:

//= require jquery
//= requi         


        
7条回答
  •  长发绾君心
    2021-02-20 09:14

    Since scripts tend to load at random orders you may force your analytics script to load after everything is up and ready.

    There are various approaches for this task.

    HTML5 rocks has given a quite nice snippet for this kind of stuff. Moreover, depending on your needs you may use a module loader like require.js. Using loading promises and Require.js is pretty sweet too. Generally, you use a lot of JavaScript a module loader will help you with this mess.

    I kept the ugliest and least efficient, still one solid approach for the end. Waiting for an external library to load may create huge bottlenecks and should be considered and also handled really carefully. Analytics fetching script is async and really hard to handle. On these cases I prefer

    Loading external deferred scripts is somehow easy:

    function loadExtScript(src, test, callback) {
      var s = document.createElement('script');
      s.src = src;
      document.body.appendChild(s);
    
      var callbackTimer = setInterval(function() {
        var call = false;
        try {
          call = test.call();
        } catch (e) {}
    
        if (call) {
          clearInterval(callbackTimer);
          callback.call();
        }
      }, 100);
    }
    

    Take a look at this example where I am loading jQuery dynamically with a promise function when the script is loaded: http://jsfiddle.net/4mtyu/487/

    Here is a chaining demo loading Angular and jQuery in order :http://jsfiddle.net/4mtyu/488/

    Considering the example above you may load your analytics as:

    loadExtScript('https://code.jquery.com/jquery-2.1.4.js', function () {
        return (typeof jQuery == 'function');
    }, jQueryLoaded);
    
    function jQueryLoaded() {
        loadExtScript('https://analytics-lib.com/script.js', function () {
            return (typeof jQuery == 'function');
        }, analyticsLoadedToo);
    }
    
    function analyticsLoadedToo() {
        //cool we are up and running
        console.log("ready");
    }
    

提交回复
热议问题