2015-06-29 47 views
1

我有這個劇本在我的頁面的最頂端我需要阻止該網頁顯示,直到腳本運行

<script type = "text/javascript"> 
if(typeof window.orientation !== 'undefined'){ var ortvalue = "defined"; } 
if(ortvalue != "defined") { 
document.location.replace("http://www.redirect-here.com"); 
} 
else { 
} 
</script> 

所有的腳本不會被檢查,如果用戶的計算機上,而不是到移動設備。如果用戶在計算機上,則該腳本會重定向到其他站點。該腳本工作正常,但有時頁面會在重定向發生之前加載並顯示一段時間。這是一個微小的細微差別,但我希望有一種方法可以防止頁面在重定向發生時顯示任何內容。

+0

假設存在「方向」意味着「移動設備」不安全。考慮Windows 8平板電腦和帶有方向傳感器的筆記本電腦。 –

回答

1

這需要一些時間重定向解析地址如果未緩存,則獲取內容並將其顯示在頁面中。這是異步發生的。

如果您可以將此腳本移動到正文標籤正下方,則可以在發生location.replace之前隱藏文檔正文。

<body> 
<script> 
var ortvalue; 
if(typeof window.orientation !== 'undefined') { 
    var ortvalue = "defined"; 
} 

if(ortvalue !== "defined") { 
    document.body.style.display = 'none'; 
    document.location.replace("http://www.redirect-here.com"); 
} 
</script> 

你說的「腳本工作正常」,否則,所以我不會改變,但可能有辦法,這可能會失敗在較新的和較新的設備。以下是檢測移動瀏覽器的其他方法的建議:Detecting a mobile browser

+1

謝謝你,用最少量的附加代碼解決了我的問題!哦,「沒有評論」正式注意到哈哈。 –

0

完成下列步驟,hide文檔,做visibility:hidden後來刪除樣式標籤如果是手機或如果不只是重定向移動設備:

document.write('<style class="hidedocument" ' + 
       'type="text/css">body {visibility:hidden;}<\/style>'); 
<script type = "text/javascript"> 
    if(typeof window.orientation !== 'undefined'){ var ortvalue = "defined"; } 
    if(ortvalue != "defined") { 
    document.location.replace("http://www.redirect-here.com"); 
    } 
else { 
var tempCheck; 
var allStyles = document.getElementsByTagName('style'); 
     var i = allStyles.length; 
     while (i >-1) { 
     tempCheck = styles[i]; 
     if (tempCheck.className == 'hidedocument') { 
      tempCheck.parentNode.removeChild(tempCheck); 
     } 
     i--;} 
} 
</script> 
0

問題是因爲location.replace對DOM加載/呈現稍有異步。 JavaScript本身是同步的執行與DOM構建內嵌。也就是說,即使頁面簡要顯示了HTML內容,JavaScript 也會運行

如果確實如此,約束中的一個解決方案可能是在調用location.replace之前將正常的主體內容「隱藏」(比如將body元素的顯示設置爲none)。

<body> 
<script> 
    if (not_on_a_mobile_device) { 
    document.body.style.display = 'none'; 
    document.location.replace("http://www.redirect-here.com"); 
    } 
</script>