由於性能原因,雅虎建議到load scripts at the bottom of an HTML pages。我使用HTML5 Boilerplate,它遵守規則。
這種方法的問題是,jQuery也加載在底部。如果由於某種原因,我需要編寫內聯JavaScript包含jQuery代碼我不能,因爲$
尚未在名稱空間中可用。
出現這種情況,例如與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>
代碼設置的#gallery
高度因爲jQuery被加載後不工作。 Firebug的控制檯提供了:
ReferenceError: $ is not defined
任何提示posticipate <script>
塊,直到$
符號執行可以在命名空間中找到?
在頂部或中間等待底部加載的內容腳本沒有意義 - 將內聯腳本移動到您在其中包含jQuery的位置之下。如果我可以大致概括一下,除非它做了一些不能等待頁面加載的內容(例如,'document.write()'),否則不應該在頁面中間需要內聯腳本。 – nnnnnn 2012-07-31 01:51:29