2013-08-16 42 views
2

我有一個視頻元素在我的頁面頂部,我想知道是否有任何方式加載它的DOM的其餘部分已被加載後?我希望視頻最後加載。加載視頻元素最後

+1

你有什麼t裏德?我的猜測是最初不定義一個源,然後使用像'if(document.readyState ===「complete」){init(); }'初始化視頻源並播放它 – Offbeatmammal

+0

聽起來不錯,我會試試看。 – Rich

+1

讓我知道它是否有幫助(如果你需要更完整的樣本),我可以把它放到答案中 – Offbeatmammal

回答

2

這似乎是做你想做的。在我的示例中,我只包含了一個mp4源文件,但您可以根據您支持的瀏覽器爲WebM和Ogg添加其他文件。您只需填充所有三個屬性,或使用canPlayType測試來確定用戶瀏覽器的最佳選擇。

的視頻元素默認爲自動播放(但你可以從<video...>標籤移除屬性,並直接從腳本控制它。它也默認爲preload="auto"讓瀏覽器控制多少預裝,你又可能要轉如果它不適合您的場景(並且不同的瀏覽器有不同的行爲)

您可能還想要隱藏視頻元素,直到您準備好加載內容爲止(儘管這會稍微擺動頁面,並且可能會看起來怪怪的用戶)

<!DOCTYPE html> 
<html> 
<head> 
<title>Initialize video when doc is ready</title> 

<script> 
document.onreadystatechange = function() { 
    console.log("readyState = " + document.readyState); 
    if (document.readyState == "interactive") { // can also wait for "complete" here 
    init(); 
    } 
} 
function init() { 
    console.log("load the source for the video element") 
    vid = document.getElementById("video") 
    // can use the vid.canPlayType test to only load supported video 
    // or have tags for MP4, WebM and Ogg to cover your bases 
    vidMP4 = document.getElementById("videoMP4") 
    vidMP4.setAttribute("src","video.mp4") 
// vid.play(); 
} 
</script> 

</head> 
<body> 

<p>Something before the video</p> 
<video id="video" controls autoplay preload="auto" width=480 height=320> 
<source id="videoMP4"></source></video> 
<p>Something after the video</p> 

</body> 
</html>