1. 程式人生 > >jTemplates非同步載入實現與HTML5 video視訊開發

jTemplates非同步載入實現與HTML5 video視訊開發

最近做有關Web App有關的專案,為了動態載入相應速度更快,採用了以下幾個策略:
1.PHP後臺提交自動生成靜態列表頁面。
2.PHP後臺提交自動生成列表頁資源/文章的json資料檔案,javascriptFileName.js。下面的17881.js。
2.列表頁滑動載入使用jTemplates讀取javascriptFileName.js資料檔案的資料進行展現。

jTemplates是一個基於JQuery的模板引擎外掛,適合用來在頁面上動態繫結資料動態生成展現資料。。在使用jTemplates時最好先定義好模板,然後將模板遷移至textarea隱藏文字框。官網地址:http://jtemplates.tpython.com/

<textarea id="txtTemplate" style="display:none">
<![CDATA[
This is {$T.name}.
]]>
</textarea>

jTemplates包含三個預定全域性變數,分別是$T、$P、$Q。$T為模板提供資料呼叫功能,$P為模板提供引數變數呼叫功能,$Q.version提供當前jTemplate的版本.
jTemplates還支援#if、#for、#cycle、#foreach、#include、#param標籤,處理實現複雜的業務。

#if 語法:
{#if |COND|}..{#elseif |COND|}..{#else}..{#/if}

#if 示例:

{#if $T.list_id} {$T.list_id} {#/if}
{#if 2*8==16} good {#else} fail {#/if}
{#if $T.age>=18)} 成人了 {#else} 未成年 {#/if}
{#if $T.list_id == 3} System list {#elseif $T.list_id == 4} Users List {#elseif $T.list_id == 5} Errors list {#/if}

#for 語法:
{#for |VAR| = |CODE| to |CODE| [step=|CODE|]}..{#else}..{#/for}

{#for |variable| = |start| to |end| [step=|stepBy|]}..{#else}..{#/for}

#for 示例:

預設步長:{#for index = 1 to 10} {$T.index} {#/for}
正向步長:{#for index = 1 to 10 step=3} {$T.index} {#/for}
負向步長及空迴圈:{#for index = 1 to 10 step=-3} {$T.index} {#else} nothing {#/for}
也可以在迴圈中使用變數:{#for index = $T.start to $T.end step=$T.step} {$T.index} {#/for}
注意條件中支援使用javascript程式碼,{#else}是在{#for...}未能執行的時的輸出內容。。

主要程式碼:

<script type="text/javascript" src="../js/jquery-jtemplates.js"></script>
<script type="text/javascript" src="../js/data.js"></script>

<textarea id="resourceTemplateContainer" style="display: none;">
{#foreach $T.Lists as row begin=$T.start count=$T.end}
	<li>
		<div class="icon">
			<img alt="{$T.row.elementname}" src="{#if $T.row.elementlogo}{$T.row.elementlogo}{#else}../img/bg72.png{#/if}" title="">
			<i class=""></i>
		</div>
		<div class="info">
			<h2>{$T.row.elementname}</h2>
			<p class="txt">{$T.row.flodertype}</p>
			<span class="arrow"></span>
			<div class="downbtn free"><a title="{$T.row.elementname}" href="{$T.row.downpath}"></a>免費下載</div>
		</div>
		<a class="down-area" title="點選檢視詳情" href="res_{#if document.getElementById("isios").value ==0}17881{#elseif document.getElementById("isios").value ==1}17941{#/if}_{$T.row.reit_url}.html"></a>
	</li>
{#/for}
</textarea>

<script type="text/javascript">
$(document).ready(function(){
	$(".bar .slidemenubtn").click(function(){
		//bug fix -chrome中的 blur事件要先呼叫focus()否則blur無效
		this.focus();
		$(".slidemenu").slideToggle("slow");
	}).blur(function(){
		$(".slidemenu").hide("slow");
	});
	var pagenum = 1 , dataFileName = '../js/17881', templateName = "resourceTemplateContainer";
	$(".ajax-wrap ul").busdata({pageSize:"10", page:1, jsName:dataFileName + ".js",template:templateName});
	$(".load-btn").click(function(){
		pagenum++;
		var con = $(".ajax-wrap ul").busdata({pageSize:"10", page:pagenum, jsName:dataFileName + ".js", template:templateName});				
	});
});
</script>

資料格式17881.js

var data = {
TotalCount:20,
Lists:[ 
{reit_url:'pv01q2',elementname:'終極狂飆3',elementlogo:'../img/res/pv01q2/element_logo_1308051724017817.png',flodertype:'你沸騰的節操將會悲催的碎一地!',downpath:'../pack/3dcar3_0820_4028.apk?n=3dcar3_0820_4028'},
{reit_url:'mgv520',elementname:'海賊王',elementlogo:'../img/res/mgv520/element_logo_1308140947295130.png',flodertype:'熱門遊戲',downpath:'../pack/dreamonepiece_feiliu_build_100537.apk?n=DreamOnePiece_feiliu_build_100537'},
]};

data.js相當於資料處理層,檔案程式碼:


(function($) {    
  // 外掛的定義    
  $.fn.busdata = function(options) {       
    // build main options before element iteration    
    var opts = $.extend({}, $.fn.busdata.defaults, options);    
    return this.each(function() {    
       var obj = $(this);
	   opts.start = (opts.page - 1) * opts.pageSize;
	   opts.end = opts.pageSize;
	   $.fn.busdata.start(obj,opts.start,opts.end,opts.template,opts.jsName);
	 
	 //$(opts.menuDiv_dom, $("#"+opts.menuDiv)).hide(opts.showSpeed);
    });    
  };
  //$.fn.busdata.n = 0;
  // 定義暴露函式    
  $.fn.busdata.start = function(obj,start,end,template,jsName) {
	 $loadbtn = $(".load-btn");
	 jQuery.ajax({	 
	  type: "get",
		 url: jsName,
		 dataType : "script",
		 beforeSend: function(){
			$loadbtn.html("<b class='loading'></b>");	//設定載入狀態圖
		 },
		 success: function(msg){	
			data.start = start;
			data.end = end;
			videoHead = "";
			
			var thisUrl = document.location.host; 
			var tip = thisUrl.split(":");
			if(thisUrl.indexOf("16wifi") > -1){
		 		videoHead =  "http://"+tip[0]+"/pack/feiliu/video";
			} else {			 
				videoHead = "http://"+tip[0]+":8090/pack/feiliu/video";			 
			}

			data.videoHead = videoHead;
			if(data.TotalCount - data.start > 0){
	 			// 設定模板
				if(template=="focusTemplateContainer"){
				$("#buttonFoucs").setTemplateElement("buttonFocusTemplateContainer");
				$("#buttonFoucs").processTemplate(data);
				}
				obj.setTemplateElement(template);
				// 處理模板
				obj.processTemplate(data);
				$loadbtn.html("點選載入更多");

			}else{
				$loadbtn.text("少年 :-) 你已瀏覽到末頁!");
				return;
			}
		   
		 },
		 complete: function(){
			//
		 }
	 })
  };  
  // 外掛的defaults    
   $.fn.busdata.defaults = {
	pageSize:10,  
    page:1,
	data:'',
    jsName: '../js/17881.js',
	template: ''
  };    
// 閉包結束  
})(jQuery);      


我們知道HTML5 <video>標籤在PC端各瀏覽器的支援不盡如人意,如果要考慮相容,需要很多種的fallback支援,如下事例:

<video onclick="this.play();" poster="../html5video/Clip_1080_5sec_10mbps_h264.jpg" width="80" height="60" title="Clip_1080_5sec_10mbps_h264">
	<source src="../html5video/Clip_1080_5sec_10mbps_h264.m4v" type="video/mp4" />
	<source src="../html5video/Clip_1080_5sec_10mbps_h264.webm" type="video/webm" />
	<object type="application/x-shockwave-flash" data="../html5video/flashfox.swf" width="80" height="60" style="position:relative;">
		<param name="movie" value="../html5video/flashfox.swf" />
		<param name="allowFullScreen" value="true" />
		<param name="flashVars" value="autoplay=true&controls=true&fullScreenEnabled=true&posterOnEnd=true&loop=false&poster=../html5video/Clip_1080_5sec_10mbps_h264.jpg&src=Clip_1080_5sec_10mbps_h264.m4v" />
		<embed src="../html5video/flashfox.swf" width="80" height="60" style="position:relative;"  flashVars="autoplay=true&controls=true&fullScreenEnabled=true&posterOnEnd=true&loop=false&poster=../html5video/Clip_1080_5sec_10mbps_h264.jpg&src=Clip_1080_5sec_10mbps_h264.m4v"	allowFullScreen="true" wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer_en" />
		<img alt="Clip_1080_5sec_10mbps_h264" src="../html5video/Clip_1080_5sec_10mbps_h264.jpg" style="position:absolute;left:0;" width="80" height="60" title="Video playback is not supported by your browser" />
	</object>
</video>				


這裡暫且不討論。而手機目前主要是

ios和android兩大陣營。如果是為手機端做開發進行視訊播放,如今已經可以大膽的使用video了。
安卓系統上HTML5 <video> 標籤
Support for HTML5:
    Database API support, for client-side databases using SQL.
    Application cache support, for offline applications.
    Geolocation API support, to provide location information about the device.
    <video> tag support in fullscreen mode.
由此可知安卓系統從Android 2.0版本就開始支援html5的video標籤,目前android手機已經普及到4.2了,使用html5 video毫無疑問條件已經非常成熟了。


而iOS很早就對audio/video標籤進行了支援,從iOS 3.0+/Safari 3.1+ 開始就已經實現了對 HTML5 video/audio 標籤的支援。因此,更不用擔心ios裝置的支援問題了。

既然兩大陣營目前都對 HTML5 video 支援的不錯,下面就說說使用中基礎知識。

支援的屬性表:

Attribute

Value

Description

preload

This attribute was formerly named autobuffer, and was boolean.

none | metadata | auto

none—Safari should not preload media data.

metadata—Safari should preload only media metadata.

automatic—Safari should preload all media data.

autoplay

Boolean—any value sets this to true

If present, asks the browser to play the media automatically.

controls

Boolean—any value sets this to true

If present, causes the browser to display the default media controls.

height (video only)

pixels

The height of the video player.

loop

Boolean—any value sets this to true

If present, causes the media to loop indefinitely. This attribute is supported in iOS 5.0 and later.

poster (video only)

url of image file

If present, shows the poster image until the first frame of video has downloaded.

src

url

The URL of the media.

width (video only)

pixels

The width of the video player.



需要注意的是
在Safri內建的控制條功能包括播放/暫停/音量/時間進度條,Safari 5.0+(桌面版) 和iOS 4.2(iPad版)右下有全屏功能按鈕。控制條播放狀態下自動消失,hover和觸控時顯示。Safari 5.1+,使用者也可以根據需要對controlls進行CSS/JavaScript開發,在全屏模式下使用自己的控制條展示。更多有關javascript和CSS3的開發知識請參考https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009523-CH1-SW1

audio/video並不支援所有音訊視訊格式,桌面版要比手機版支援的格式更多,Safari支援基於HTTP Live Streaming協議的流媒體傳輸,而其他瀏覽器只支援基於HTTP的檔案下載播放。
支援格式:
    H.264 Baseline Profile Level 3.0 video, up to 640 x 480 at 30 fps. Note that B frames are not supported in the Baseline profile.

    MPEG-4 Part 2 video (Simple Profile)

    AAC-LC audio, up to 48 kHz
對應字尾名.mov, .mp4, .m4v, and .3gp

檔案字尾與MIME型別對應:

Extensions

MIME type

.mov

video/quicktime

.mp4

video/mp4

.m4v

video/x-m4v

.3gp

video/3gpp


Android和iOS的Browser目前對HTML5和CSS3的支援都很有限,即使是Chromium最新版本對HTML5也不是完全支援。
可以在手機瀏覽器開啟這個網站測試一下對HTML5功能和API的支援情況 html5test.com/

補充:


HTTP Live Streaming(縮寫是 HLS)是一個由蘋果公司提出的基於HTTP的流媒體 網路傳輸協議。是蘋果公司QuickTime X和iPhone軟體系統的一部分。它的工作原理是把整個流分成一個個小的基於HTTP的檔案來下載,每次只下載一些。當媒體流正在播放時,客戶端可以選擇從許多不同的備用源中以不同的速率下載同樣的資源,允許流媒體會話適應不同的資料速率。在開始一個流媒體會話時,客戶端會下載一個包含元資料的extended M3U (m3u8) playlist檔案,用於尋找可用的媒體流。

參考文章:
Audio and Video HTML】https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/AudioandVideoTagBasics/AudioandVideoTagBasics.html#//apple_ref/doc/uid/TP40009523-CH2-SW6
Creating Video】https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/CreatingVideoforSafarioniPhone/CreatingVideoforSafarioniPhone.html