延迟功能直到$可用

Pao*_*olo 1 javascript jquery namespaces deferred-execution

出于性能原因,雅虎建议在HTML页面底部加载脚本.我使用符合规则的HTML5 Boilerplate.

这种方法的问题是jQuery也在底部加载.如果由于某种原因我需要编写包含jQuery代码的内联javascript,我不能,因为$在命名空间中还没有.

例如,使用galleria.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>
Run Code Online (Sandbox Code Playgroud)

设置高度的代码#gallery不起作用,因为稍后加载jQuery.Firebug控制台给出:

ReferenceError: $ is not defined
Run Code Online (Sandbox Code Playgroud)

是否可以在命名空间中找到符号,<script>直到$符号被执行为止?

Bra*_*och 5

将jQuery <script>标记保留在底部,然后将Galleria移到其<script>下方.

<script type="text/javascript" src="jquery.js"></script>
<script>
$('#gallery').css('height', '200px'); // this is required for galleria to work
Galleria.run('#gallery');
</script>
Run Code Online (Sandbox Code Playgroud)