等待从CDN加载Javascript [英] Wait for Javascript load from CDN

查看:100
本文介绍了等待从CDN加载Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails应用程序中启用了Turbo链接,并使用了以下JavaScript代码块:

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>

通常,我会得到错误消息,即.dataTable()函数未定义,而刷新可以解决该问题.但是,刷新并不总是令人满意,因此我添加了100ms的setTimeout以等待CDN中的js加载.

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.

到目前为止,在我的开发环境中我看不到任何问题,但是我担心如果客户端速度慢,js将无法在100ms内完成加载. 我想知道是否有更好的方法来解决此问题,例如检查两个js文件是否已加载,类似于$(document).ready for DOM.

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.

谢谢!

推荐答案

我找到的最优雅的方法是将所有cdn链接移至中的布局页面,以便所有库都将被加载和缓存整个用户体验.

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.

这篇关于等待从CDN加载Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆