【发布时间】:2012-07-28 17:43:39
【问题描述】:
出于性能原因,雅虎建议load scripts at the bottom of an HTML pages。我使用符合规则的 HTML5 Boilerplate。
这种方法的问题是 jQuery 也是在底部加载的。如果由于某种原因我需要编写包含 jQuery 代码的内联 javascript,我不能,因为 $ 在命名空间中尚不可用。
例如,galeria.js(jQuery 图片库引擎)会发生这种情况,它需要此标记:
<div id="gallery">
<img src="/media/img1.png" />
<img src="/media/img2.png" />
</div>
<script>
$('#gallery').css('height', '200px'); // this is required for galleria to work
Galleria.run('#gallery');
</script>
设置#gallery 高度的代码不起作用,因为稍后会加载 jQuery。 Firebug 控制台给出:
ReferenceError: $ is not defined
在命名空间中可以找到 $ 符号之前,是否有任何提示可以预测 <script> 块的执行?
【问题讨论】:
-
没有必要在顶部或中间放置内联脚本来等待底部的内容加载 - 将内联脚本移动到包含 jQuery 的位置下方。如果我可以进行全面概括,那么您不需要页面中间的内联脚本,除非它执行的操作无法等待页面加载(例如,
document.write())。
标签: javascript jquery namespaces deferred-execution