Я прочитал много сообщений здесь и на других сайтах, посвященных обнаружению браузера и обнаружению функций, и я понимаю все плюсы обнаружения функций. Однако я столкнулся с проблемой, в которой обнаружение браузера может быть правильным ответом. Тестируя реализацию HTML5 моего сайта в Safari по сравнению с другими браузерами, я пришел в ужас от времени загрузки. Для конкретной страницы, которую я тестировал с видео HTML5, вот время загрузки:
Хром: 4 сек. Firefox: 3 секунды. IE9: 4 секунды. Safari 5.1.7 (для ПК, пробовал три раза): 1м 12с, 1м 4с, 1м 3с, 57с (?!?!)
Я пытался найти какие-либо разумные объяснения, так как многие другие наблюдали ту же проблему в Safari (по крайней мере, v. 5.1.7), но ничего из того, что я мог найти, не появилось. Несмотря на то, что Safari технически «поддерживает» HTML5, я не могу с чистой совестью оставить его таким для своих зрителей. У меня уже есть код и медиафайлы для показа Flash-видео через SWFOBJECT для браузеров, не поддерживающих HTML5 (запускается с помощью проверки JS "canPlayType"). Я открыт для других предложений, но на данный момент мне кажется, что мне нужно специально предоставить Flash-видео и пользователям Safari. Я никогда не писал/не тестировал код обнаружения браузера, и я знаю, что это сложный процесс. Итак, если это лучший маршрут, какой код JavaScript для этого будет лучшим? Если есть лучшее решение, которое я должен рассмотреть, то обязательно передайте его!
Вот динамический HTML, который мой JS обслуживает для браузеров с поддержкой видео HTML5:
<html><head>
<meta charset="UTF-8">
<meta content="David Kinsey" name="author">
<meta content="David Kinsey" name="designer">
<meta content="general" name="rating">
<meta content="noindex,nofollow" name="robots">
<title>David Kinsey: Volleyball Scorekeeping Assessment Demo</title>
<!-- global stylesheets -->
<link href="/css/layers.css" type="text/css" rel="stylesheet">
<link href="/css/layout.css" type="text/css" rel="stylesheet">
<link href="/css/nav.css" type="text/css" rel="stylesheet">
<!-- scaleSWF css
<link rel="stylesheet" type="text/css" href="/css/scaleSWF.css" /> -->
<script src="/javascript/global.js" type="text/javascript"></script>
<script src="/javascript/swfobject.js" type="text/javascript"></script>
<script src="/javascript/genVideo.js" type="text/javascript"></script>
</head>
<body id="defaultBody">
<!-- create top banner full-width of page -->
<div id="banner_top">
<script src="/javascript/genHeader.js" type="text/javascript"></script><div id="banner_bar"></div><img alt="Banner graphic of my name, David Kinsey" src="/images/bannerMyName.png" id="banner_myname"><a href="http://www.davidkinsey.me/index.htm" class="noOutline" id="homeLink"><img "="" alt="Logo of my initials, DLK" src="/images/DLKlogo-SMALL.png" class="noOutline" id="DLKlogo"></a><img alt="Banner graphic of my title, Instructional Designer" src="/images/instructDesigner.png" id="banner_title">
</div>
<video width="826" height="616" id="videoTag" preload="auto" controls="controls" poster="/images/logoAnimationStill.png" class="centeredMedia" autoplay="true" tabindex="0" style="visibility: visible;">
<source src="http://www.davidkinsey.me/video/demoAssessment.mp4" type="video/mp4"></source>
<source src="http://www.davidkinsey.me/video/demoAssessment.webm" type="video/webm"></source>
</video>
</body>
</html>
А вот динамический альтернативный HTML для Flash-видео SWFOBJECT:
<html><head>
<meta charset="UTF-8">
<meta content="David Kinsey" name="author">
<meta content="David Kinsey" name="designer">
<meta content="general" name="rating">
<meta content="noindex,nofollow" name="robots">
<title>David Kinsey: Volleyball Scorekeeping Assessment Demo</title>
<!-- global stylesheets -->
<link href="/css/layers.css" type="text/css" rel="stylesheet">
<link href="/css/layout.css" type="text/css" rel="stylesheet">
<link href="/css/nav.css" type="text/css" rel="stylesheet">
<!-- scaleSWF css
<link rel="stylesheet" type="text/css" href="/css/scaleSWF.css" /> -->
<script src="/javascript/global.js" type="text/javascript"></script>
<script src="/javascript/swfobject.js" type="text/javascript"></script>
<script src="/javascript/genVideo.js" type="text/javascript"></script>
</head>
<body id="defaultBody">
<!-- create top banner full-width of page -->
<div id="banner_top">
<script src="/javascript/genHeader.js" type="text/javascript"></script><div id="banner_bar"></div><img alt="Banner graphic of my name, David Kinsey" src="/images/bannerMyName.png" id="banner_myname"><a href="http://www.davidkinsey.me/index.htm" class="noOutline" id="homeLink"><img "="" alt="Logo of my initials, DLK" src="/images/DLKlogo-SMALL.png" class="noOutline" id="DLKlogo"></a><img alt="Banner graphic of my title, Instructional Designer" src="/images/instructDesigner.png" id="banner_title">
</div>
<object width="805.2389380530973" height="616" type="application/x-shockwave-flash" data="demoAssessment_controller.swf" id="flashcontent" style="visibility: visible;" class="centeredMedia" autoplay="true">
<param name="bgcolor" value="333333">
<param name="quality" value="best">
<param name="allowscriptaccess" value="always">
<param name="flashvars" value="csConfigFile=demoAssessment_config.xml&csColor=333333&csPreloader=demoAssessment_preload.swf&csFilesetBookmark=0">
</object>
</body>
</html>
Вот соответствующий код JavaScript:
function addVideoSources(pageName, vid) {
var newMP4 = document.createElement("source");
var newWebm = document.createElement("source");
newMP4.setAttribute("src", containerID + pageName + ".mp4");
newMP4.setAttribute("type", "video/mp4");
newWebm.setAttribute("src", containerID + pageName + ".webm");
newWebm.setAttribute("type", "video/webm");
vid.appendChild(newMP4);
vid.appendChild(newWebm);
}
function addVideoAttributes(pageName, vid) {
vid.setAttribute("id", "videoTag");
vid.setAttribute("preload", "auto");
vid.setAttribute("controls", "controls");
vid.setAttribute("poster", "/images/logoAnimationStill.png");
if (pageName != "index") {
vid.setAttribute("class", "centeredMedia");
vid.setAttribute("autoplay", "true");
} else {
vid.setAttribute("class", "rightSideMedia");
}
vid.addEventListener('loadstart', loadstarted, false);
vid.addEventListener('loadedmetadata',
function() {
if (document.getElementById("noJavaScript")) {
obj = document.getElementById("noJavaScript");
obj.parentNode.removeChild(obj);
}
sizeVideo(pageName, this, this.videoWidth, this.videoHeight, this.offsetTop);
}, false);
vid.addEventListener('error', failed, false);
}
function appendVideoObj(vidObj) {
var contentCol = document.getElementById("contentCol");
if (contentCol) {
contentCol.insertBefore(vidObj, contentCol.firstChild);
} else {
document.body.appendChild(vidObj);
}
}
function insertHTML5Video() {
var newVid = document.createElement("video");
var pageName = getPageName();
addVideoAttributes(pageName, newVid);
addVideoSources(pageName, newVid);
appendVideoObj(newVid);
}
function swfObjectLoadedHandler(e) {
// alert("e.success = " + e.success +"\ne.id = "+ e.id +"\ne.ref = "+ e.ref);
var obj = new Object();
var pageName = getPageName();
if (pageName != "index") {
e.ref.setAttribute("class", "centeredMedia");
e.ref.setAttribute("autoplay", "true");
} else {
e.ref.setAttribute("class", "rightSideMedia");
}
if (e.success) {
if (document.getElementById("noJavaScript")) {
obj = document.getElementById("noJavaScript");
obj.parentNode.removeChild(obj);
}
sizeVideo(pageName, e.ref, e.ref.width, e.ref.height, e.ref.offsetTop);
} else {
obj = document.getElementById("videoLayer");
alert("Movie load failed. Please try again by refreshing your browser.");
}
}
function insertSWFobject() {
var flashcontent = document.createElement("div");
var req = swfobject.hasFlashPlayerVersion("9.0.115");
var bookmark = args.movie ? args.movie : 0;
var pageName = getPageName();
var cs_noexpressUpdate = document.createElement("div");
var noFlashPlayerPara = document.createElement("p");
var noFlashPlayerText1 = document.createTextNode("I'm sorry, but the video content for this page requires Adobe Flash Player® version 9 or higher to be installed on your computer. You can download the latest version of Flash Player® for free by visiting ");
var flashPlayerLink = document.createElement("a");
var noFlashPlayerLinkText = document.createTextNode("Adobe's Flash Player® download page");
var noFlashPlayerText2 = document.createTextNode('. If you have the player installed, verify that your browser has JavaScript enabled. You can find easy-to-follow instructions how to do this by using Google® with the words "enable JavaScript" in the search box. Thank you!');
flashcontent.setAttribute("id", "flashcontent");
flashcontent.setAttribute("class", "noJavaScript");
appendVideoObj(flashcontent);
if (req ) {
swfobject.embedSWF(pageName + "_controller.swf", "flashcontent", vidSpecs[pageName].width, vidSpecs[pageName].height, "9.0.115", null, { csConfigFile: pageName + "_config.xml", csColor: "333333", csPreloader: pageName + "_preload.swf", csFilesetBookmark: bookmark }, { bgcolor: "333333", quality: "best", allowscriptaccess: "always" }, null, swfObjectLoadedHandler );
} else {
flashPlayerLink.setAttribute("href", "http://www.adobe.com/go/getflashplayer");
flashPlayerLink.appendChild(noFlashPlayerLinkText);
noFlashPlayerPara.setAttribute("class","noFlashPlayerText");
noFlashPlayerPara.appendChild(noFlashPlayerText1);
noFlashPlayerPara.appendChild(flashPlayerLink);
noFlashPlayerPara.appendChild(noFlashPlayerText2);
flashcontent.appendChild(noFlashPlayerPara);
}
}
function getClientWidth() {
return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}
function getClientHeight() {
return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}
function onloadHandler() {
var obj = document.getElementById("noJavaScript");
var vidElem = document.createElement("video");
getBrowserInfo();
obj.parentNode.removeChild(obj);
if ((vidElem.canPlayType) && uaNotSafari()) { // if browser has HTML5 video support and is NOT CRAPFARI use HTML5 video
insertHTML5Video()
} else { // no video tag support; use SWFobject
insertSWFobject(); // otherwise use Flash video via SWFOBJECT
}
} /* END onloadHandler */
addLoadEvent(onloadHandler); // requires global.js to be included in same document
Спасибо, - ДК