【发布时间】:2016-04-05 02:33:20
【问题描述】:
我正在尝试为datatables.min.js 编写一个 CDN 后备——不知何故,我在 Google 或 datatables.net 上找不到任何内容。在阅读了这个StackOverflow post和这个DataTables post之后,我想出了这个不成功的文章(甚至尝试了如图所示的各种表达方式):
<script>
if (typeof jQuery.fn.dataTable === 'undefined') {
document.write('<script src="~/scripts/datatables.min.js"><\/script>');
//document.write('<script src="~/scripts/datatables.min.js">\x3C/script>'); //same
//document.write('\x3Cscript src="~/scripts/datatables.min.js"\x3E\x3C/script\x3E'); //same
}
</script>
为了排查问题,我直接加载了datatables.min.js,得到了这两个令人困惑的结果:
1/ 我从这里得到undefined (BAD):
<script>
document.write('<script src="~/scripts/datatables.min.js"><\/script>');
</script>
<script>
alert(typeof jQuery.fn.dataTable);
</script>
2/ ...但不知怎的,我从中得到了function (GOOD):
<script src="~/scripts/datatables.min.js"></script>
<script>
alert(typeof jQuery.fn.dataTable);
</script>
这在我看来是一样的,尤其是document.write 使用同步加载。我也尝试了纯 DOM 方法,但没有运气。
document.write 缺少什么?
【问题讨论】:
-
您正在将
script插入到script中的<script> document.write('<script src="~/scripts/datatables.min.js"><\/script>'); </script>中 -
使用
$.getScript('~/scripts/datatables.min.js?' + Math.random(), function () { });动态加载脚本。 -
document.write方法已被普遍使用和推荐 - 例如请参阅 jQuery 的 CDN 后备 (stackoverflow.com/questions/5257923/…)。我认为这不是问题。 -
@ParthTrivedi - 我试过 $.getScript 但它也不起作用。它甚至返回一个新的
404 Not Found错误。 -
"~/scripts/datatables.min.js"路径可能有问题。它找不到它并获取404。能否请您验证路径。
标签: javascript jquery datatables cdn fallback