Wait for Javascript load from CDN

﹥>﹥吖頭↗ 提交于 2019-12-13 05:14:32

问题


I have this block of javascript in a Rails app, with turbo-link enabled:

<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/plug-ins/be7019ee387/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<script type="text/javascript" charset="utf-8">
    var ready = function() {
    setTimeout(function() {
      $('#table-products').dataTable();
    }, 100);
    };
    $(document).on('ready, page:change', ready);    
</script>

Usually, I get the error that the .dataTable() function is undefined, and a refresh can solve the problem. However, refresh is not always pleasant, so I added the setTimeout for 100ms to wait for the js from CDN to load.

So far I don't see any issue in my dev environment, but I am afraid that if there is a slow client, the js won't finish loading within 100ms. I wonder if there would be a better way to solve this, like checking if the two js files have been loaded, similar to $(document).ready for DOM.

Thanks!


回答1:


There's actually a gem for this. It's really easy to use and comes with bootstrap styling options. This is more elegant than what you have because it doesn't rely on CDNs and instead leverages the Rails asset pipeline.




回答2:


Try

<head>
<script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/plug-ins/be7019ee387/integration/bootstrap/3/dataTables.bootstrap.js"></script>

<script type="text/javascript" charset="utf-8">
$.holdReady(true);
var s = setInterval(function() {
  if ($.fn.hasOwnProperty("DataTable") 
      && typeof $.fn.DataTable === "function") {
        $.holdReady(false);
        clearInterval(s);
  };
 }, 1); 
$(document).ready(function() {
  $("#table-products").dataTable();
});  
</script>
</head>

jsfiddle http://jsfiddle.net/guest271314/RZVRL/

See https://api.jquery.com/jQuery.holdReady/




回答3:


The most elegant way I can find is to move all the cdn links to the layout page in the , so that all the libraries will be loaded and cached for the entire user experience.



来源:https://stackoverflow.com/questions/24598840/wait-for-javascript-load-from-cdn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!