2013-10-20 32 views
6

我有一個頁面上有大約100個視頻(youtube)加載iframe。他們都在手風琴風格的菜單中,我想知道是否有方法讓他們在手風琴開啓或頁面上可見iframe時加載。現在它佔用太多內存並且滯後頁面很多。iframe加載時可見

+0

您能確定每個手風琴項目何時開放嗎?或者你能提供打開每個項目的JS和一些顯示至少一個手風琴項目的HTML嗎? – Popnoodles

回答

8

您尚未顯示任何允許我們在代碼中包含此代碼的代碼。

不要設置視頻的SRC,將其存儲在數據

<iframe src="about:blank" data-src="http://youtu.be/etc"></iframe> 

使用任何觸發手風琴,$(本)在於手風琴項目

var $iframe=$(this).find('iframe'); 
if ($iframe.data('src')){ // only do it once per iframe 
    $iframe.prop('src', $iframe.data('src')).data('src', false); 
} 
0

如果你想這樣做,你可以設置iframe的src屬性,它指向視頻,當手風琴打開時觸發的事件。我還沒有和手風琴一起工作,但很確定有一個初始事件。

+3

評論!=答案 – Popnoodles

+1

嗯,在某處使用代碼編寫代碼並不總是上帝。受益的因素是研究,並給他們看看。我的想法。當代碼發佈時,他們需要一部分幫助,然後發佈代碼修復或完成。當問題是問一個方向時,我給他們一個方向。比浪費評論沒有理由,但有爭議的事情更好。 :) – Casey

+0

在這裏,檢查iframe是否可點擊,是這樣,那意味着它被加載。然後,設置手風琴觸發事件的內容。發佈一些代碼,並且可以爲您編寫一些特定的內容,以瞭解如何合併這種方法。 – Casey

1

好了,所以它將如下:

HTML

<div id="accordion"> 
    <h3>Video 1</h3> 
    <div class="content" data-link="//www.youtube.com/embed/nlcIKh6sBtc"> 
     <iframe width="200" height="200" src="" frameborder="0"></iframe> 
    </div> 

    <h3>Video 2</h3> 
    <div class="content" data-link="//www.youtube.com/embed/My2FRPA3Gf8"> 
     <iframe width="200" height="200" src="" frameborder="0"></iframe> 
    </div> 

    <h3>Video 3</h3> 
    <div class="content" data-link="//www.youtube.com/embed/CevxZvSJLk8"> 
     <iframe width="200" height="200" src="" frameborder="0"></iframe> 
    </div> 
</div> 

的JavaScript

var elements = document.getElementsByClassName("content"), bubbles = false; 

var observer = new WebKitMutationObserver(function (mutations) { 
    mutations.forEach(attrModified); 
}); 

for(var i = 0; i < elements.length; i++){ 
    observer.observe(elements[i], { attributes: true, subtree: bubbles }); 
} 

function attrModified(mutation) { 
    var contentStyle = mutation.target.getAttribute("style"); 
    var IsVisible = contentStyle.indexOf("block") != -1; 
    if(!IsVisible){ 
     var $currentIframe = $(mutation.target).children("iframe"); 
     $currentIframe.attr("src", ""); 
    } 
    else{ 
     var link = $(mutation.target).data("link"); 
     var $currentIframe = $(mutation.target).children("iframe"); 
     $currentIframe.attr("src", link); 
    } 
} 

$("#accordion").accordion(); 

例子:AccordionLoadFrame

0

對於那些誰正在尋找這個問題的答案,另一種解決方案是增加lazyloadË適合內容。可以使用jQuery LazyLoad Any庫來實現相同。圖書館也有例如。渲染YouTube Video