js防阻塞載入,js阻塞載入

來源:互聯網
上載者:User

js防阻塞載入,js阻塞載入

js防阻塞載入

<script type="text/javascript">function scriptDomElement (u) {  var s = document.createElement('script');  h = document.getElementsByTagName('body')[0];  s.src = u;  s.async = true;  if(h)h.appendChild(s,h.firstChild);}scriptDomElement('http://*************************?t=20140717');</script>



javascript載入的問題,無阻塞指令碼

這個不能一概而論,如果你頁面外鏈元素比較少或沒有的話,是不會出現下載阻塞的。如果你的頁面引用的外部檔案如css,圖片等比較多的話,你把所有指令碼直接寫在頁面的script標籤裡(即使是在body標籤結束的下面)而非外鏈時,也是有可能出現指令碼運行時外部的css檔案還沒下載完畢。一般的情況頁面初始化要執行的方法,會寫在onload事件中。
 
動態載入JS過程中怎判斷JS載入完成

在正常的載入過程中,js檔案的載入是同步的,也就是說在js載入的過程中,瀏覽器會阻塞接下來的內容的解析。這時候,動態載入便顯得尤為重要了,由於它是非同步載入,因此,它可以在後台自動下載,並不會妨礙其它內容的正常解析,由此,便可以提高頁面首次載入的速度。
在IE或一些基於IE核心的瀏覽器中(如Maxthon),它是通過script節點的readystatechange方法來判斷的,而其它的一些瀏覽器中,往往是通過load事件來決定的,如下代碼:
function dynamicLoad(){var _doc=document.getElementsByTagName('head')[0];
var script=document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('src','jquery-1.4.4.js');
script.onload=script.onreadystatechange=function(){
if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
alert('done');}script.onload=script.onreadystatechange=null;}}
這是因為,如果script節點沒有添加到DOM樹中,那麼在chrome和firefox中是不會響應script的load事件的。但是IE中卻可以。。修改後如下代碼:
function dynamicLoad(){var _doc=document.getElementsByTagName('head')[0];
var script=document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('src','jquery-1.4.4.js');
_doc.appendChild(script);
script.onload=script.onreadystatechange=function(){
if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
這時候,所有的瀏覽器都可以響應,你可以嘗試一下~
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.