Javascript includes not loading for later in the page

前端 未结 7 2670
我寻月下人不归
我寻月下人不归 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:19

    As others have described, you are loading scripts and then trying to execute code before your scripts have finished loading. Since this is an occasionally intermittent error around a relatively small amount of code located in your HTML, you can fix it with some simple polling:

    (function runAnalytics () {
      if (typeof analytics === 'undefined') {
        return setTimeout(runAnalytics, 100);
      }
      analytics.track('on that awesome page');
    }());
    

    ... the same can be used for other libraries, hopefully you see the pattern:

    (function runJQuery () {
      if (typeof $ === 'undefined') {
        return setTimeout(runJQuery, 100);
      }
      $(document).ready(...);
    }());
    

    Edit: As pointed out in the comments, the load events would be better suited for this. The problem is that those events might have already fired by the time the script executes and you have to write fallback code for those scenarios. In favor of not writing 10+ lines of code to execute 1 line, I suggested a simple, non-invasive, quick and dirty, sure to work on every browser polling solution. But in order to not get any more downvotes, here's a more proper tedious and over complicated solution in case you have some beef with polling:

    <script>
    // you can reuse this function
    function waitForScript (src, callback) {
      var scripts = document.getElementsByTagName('script');
      for(var i = 0, l = scripts.length; i < l; i++) {
        if (scripts[i].src.indexOf(src) > -1) {
          break;
        }
      }
      if (i < l) {
        scripts[i].onload = callback;
      }
    }
    
    function runAnalytics () {
      analytics.track('on that awesome page');
    }
    
    if (typeof analytics === 'undefined') {
      waitForScript('analytics.js', runAnalytics);
    } else {
      runAnalytics();
    }
    
    function runJQuery () {
      $(document).ready(...);
    }
    
    if (typeof $ === 'undefined') {
      waitForScript('jquery.min.js', runJQuery);
    } else {
      runJQuery();
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题