我在标题
中调用了几个CDN
个文件
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/scriptaculous/1.8.2/scriptaculous.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
并且在我的所有js文件之后依赖于这个库, 但谷歌的页面速度抱怨这些脚本在页面加载时是阻止者。所以我试图在关闭之前放置所有内容,但在这种情况下,我会破坏所有脚本,因为它们依赖于jquery。
我尝试使用defer
,但与页脚中的问题相同。如何加载异步javascript库以免破坏漏洞?
答案 0 :(得分:2)
一般解决方案是使用像RequireJS这样的异步模块加载。这是一个jQuery集成案例:http://requirejs.org/docs/jquery.html
考虑“但在这种情况下,我将破坏所有脚本,因为它们依赖于jquery。”您可以在JS代码中添加检查,如:
$(document).ready(function(){
//your jQuery-based code
})
//if jQuery loading failed
if(!window.jQuery){
}
答案 1 :(得分:0)
您可能希望查看同一主机中的文件数。请看this。
答案 2 :(得分:0)
您希望实现 AMD (异步模块定义)
异步模块定义(AMD)是一种JavaScript规范,它定义了用于定义代码模块及其依赖关系的API,并在需要时异步加载它们。 了解详情:https://en.wikipedia.org/wiki/Asynchronous_module_definition
有很多框架可供选择:
或者您可以使用此方法手动加载JS文件(不推荐): https://stackoverflow.com/a/7719185/1502230