how do i make a flash element mobile friendly with javascript? - javascript

if I have a site that has a flash header, but it's not mobile friendly on apple products and even some androids, what is the javascript code I can insert into my .html page so that it doesn't show this when it is loaded...
What I'm trying to fix:

You can try using HTML5's innerHTML option with JavaScript to check whether Flash is available or not. From that info, you could then show alternative content like some image file if the device cannot display an .swf file (Flash app).
Since you did not show any code of your own page header setup, I'll show a basic example and maybe you can apply logic to your own page.
Put code in blank document (edit widths/heights) and save as .html.
In your browser block Flash and refresh... it shows image banner.
In your browser **enable* Flash and refresh... it shows Flash banner.
Test this code and ask any questions for clarification:
<!DOCTYPE html>
<html>
<body>
<div id="my_Banner"></div>
</body>
<script>
var show_A = '<embed width=600 height=200 src="https://www.w3schools.com/tags/helloworld.swf">';
var show_B = '<img width=600 height=200 src="https://www.videocopilot.net/blog/wp-content/uploads/2013/03/trap.jpg"/>';
function isFlashEnabled()
{
var flash = navigator.plugins.namedItem('Shockwave Flash');
if (!flash) { return 0; }
else { return 1; }
}
if( isFlashEnabled() ) //if Flash is availabe as browser plugin
{ document.getElementById('my_Banner').innerHTML = show_A; }
else //if Flash not availabe as browser plugin (eg: on mobile browsers)
{ document.getElementById('my_Banner').innerHTML = show_B; }
</script>
</html>

Related

Allow javascript inside iframe (Adding html file from google webdesigner)

We have many animations generated by Google webdesigner which popups when user click on some td element.
I've found that the only way to add these animations is have a iframe, so we have a fixed iframe where we update src with these animations
Edit.cshtml:
<iframe id="popUpFrame"></iframe>
<script src="~/js/popUp/popUp.js"></script>
On end of this file we have several "apps" created by Google webdesigner (generated to html file)
Element with id 01 is td element which listen on click
// PopUps
let frame_elem = document.getElementById("popUpFrame")
//speedtest popup-01
let speedtest_elem = document.getElementById("01")
hoPopUp(frame_elem, speedtest_elem, "505px", "505px", "/images/PopUps/01.html")
popup.js file:
function hoPopUp(frame_elem, td_elem, width, height, file_path){
frame_elem.style.width = width
frame_elem.style.height = height
frame_elem.style.top = "50%"
frame_elem.style.left = "50%"
td_elem.addEventListener("click", function () { showIframe(frame_elem, file_path) })
td_elem.addEventListener("mouseout", function () { hideIframe(frame_elem) })
}
function showIframe(frame_elem, file_path) {
frame_elem.setAttribute("src", file_path)
frame_elem.classList.add("active")
}
function hideIframe(frame_elem){
frame_elem.classList.remove('active')
frame_elem.removeAttribute('src')
}
The google webdesigner html file is full of javascript code, but I dont know how to allow it. We've found out that Add blocker is blocking it so we create detection of add blocker by sending some fetch request to some add, but my colleague is using uBlocker where the detection mechanism is not working.
Question is, how to allow running the javascript inside the iframe. Why are the browser tools blocking javascript "downloaded" from my own website?
Thank you for help
uBlocker is doing some "cosmetic filtering", so add detection by sending some javascript fetch Request doesnt work...
Instead of trying detect browser's tool, we put a note to every webdesigner generated html code:
<body>
<div style="width: 100%; position:absolute; top:50%;">
<p style="display:flex; justify-content:center;">
Please disable add blocker and content filters on this site
</p>
</div>
If the javascript is allowed to run inside the iframe with the webdesigner html code, the animation will be over this note

Prevent iframe from loading on mobile

I am working on my portfolio page and I want to have my projects in a demo mode where the user can preview the sites in different viewports. I got the idea from here:
http://my.studiopress.com/themes/genesis/#demo-full
On mobile devices I would like to keep the iframes from loading, and instead have links to the projects open the sites in the new tab.
If I have the divs containing the iframes hidden at the very top of my CSS file with display:none, I can see the iframes still load in the background and the page takes a long time to load.
Is there any way to keep them from loading at all when on a certain device or viewport size?
You could achieve this by using JavaScript and the HTML Data-Attribut. By setting the src-Attribute to something like "#" it won't load anything. You can use the data-Attribute to store the URL for use with JavaScript.
<iframe src="#" data-src="https://placekitten.com/200/300" frameborder="0"></iframe>
Then you just check to screen size with window.matchMedia() and set the src-attribute at a specific screen size.
var $iframe = $('iframe'),
src = $iframe.data('src');
if (window.matchMedia("(min-width: 480px)").matches) {
$iframe.attr('src', src);
}
Here is a working example: https://jsfiddle.net/5LnjL3uc/
If you want to show the iframe after a user resizes the window you need to put your code into a function and bind it to a resize event:
var $iframe = $('iframe'),
src = $iframe.data('src');
function showIframe() {
if (window.matchMedia("(min-width: 480px)").matches) {
$iframe.attr('src', src);
}
}
$(window).on('resize', showIframe);
// Initialize it once on document ready
showIframe();
Working Example: https://jsfiddle.net/5LnjL3uc/1/
A better solution is to approach this in reverse.
IE do not load the src to begin with by placing your URL in a attribute like 'data-src' for example.
See my code for this below. You simply copy the data-src to your src when your device, or device width is not mobile/mobile size.
I believe this is the best solution because there are no uncertainties. With the previously mentioned solutions (which I tried) you are racing against the clock with the browser for when your code runs and it decides to load the iframe src.
if(device !== true) {
// add '#' to the href
let iframe = document.getElementById('3dExperience')
iframe.src = iframe.getAttribute('data-src')
}
Note: 'device' is the is-mobile npm package for detecting mobile.

Start multiple downloads and get feedback when download prompt window showed

I'm currently writing a little program that generates an html file and opens it with the default browser to start multiple downloads.
I don't want to open a tab/window for every download, so creating hidden iframes for the downloads seemed like a good solution.
I'm using onload on the iframes to find out if the download prompts for each download have shown up yet. This approach seems to be very unreliable in the Internet Explorer though.
So I'm wondering if there is there a way to fix this or maybe a better approach?
(Without libraries please.)
Here is my html/js code:
<!DOCTYPE html>
<!-- saved from url=(0016)http://localhost -->
<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Downloads</title>
<script>
"use strict";
var downloadsInfo = {
"http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe":"Status: Connecting",
"http://download.piriform.com/ccsetup410.exe":"Status: Connecting"
};
var i = 0;
var iv = setInterval(function() {
i = ++i % 4;
var j = 0;
var finished = true;
for (var key in downloadsInfo) {
var value = downloadsInfo[key];
if (value != "Status: Download Started!") {
value = value+Array(i+1).join(".");
finished = false;
}
document.getElementsByTagName("div")[j].innerHTML = key+"<br/>"+value;
j = j+1;
}
if (finished) {
alert('Done! You can close this window/tab now.');
clearInterval(iv);
}
}, 800);
</script>
</head><body>
<h3>Please wait for your downloads to start and do not reload this site.</h3>
<div></div> <br/><br/>
<div></div> <br/><br/>
<iframe src="http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe" onload="downloadsInfo['http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe'] = 'Status: Download Started!';" style="display:none"></iframe>
<iframe src="http://download.piriform.com/ccsetup410.exe" onload="downloadsInfo['http://download.piriform.com/ccsetup410.exe'] = 'Status: Download Started!';" style="display:none"></iframe>
</body></html>
Quite simply you can't know whether a native browser download started. Every browser has different ways this is handled, the user may set up his browser to prompt the location or he might just let it auto download to the Downloads folder (the default in most browsers nowadays). If he's prompting for a location he might cancel by mistake, yet your setup would still claim the download started. So, no, there is no way whatsoever to reliably inform the user that they can close a tab once all downloads are started/finished... provided that you use the native browser download mechanism.
The way to achieve this effect would be possibly by first downloading the file using Javascript (requiring you to have access to those files, hotlinking to third party files is of course not an option then). To see this in action try downloading a file from mega.nz. I was planning on writing up how to do this by hand, but there is already a nice (quite outdated) answer outlining this.
If the intention is only to ensure that the download has started you could implement a trigger on the back end to note when the file has been accessed. In it's simplest form this would look like:
Page download.html requests file.php?location=[...]&randomHash=1234
Once file.php is actually loaded it will set a flag in memory or the database that randomHash id 1234 has started.
file.php redirects the page with a 302 header to the actual file location.
download.html checks periodically using Ajax whether flag randomHash=1234 has been raised. If so it knows the download has started.
Indeed IE is reported to not always behave nicely with the onload event handler of iframes. There is an active bug tracker record opened.
The problem is discussed in a number of places around the web, and what seems to be the most reliable solution is to have an indirect download with nested iframes: the iframe loads a HTML file with an iframe that loads the file to download. The reason for that is that IE does not seem to like iframes that point to something else than HTML. So if you have the possibility to do that in your program:
For each file to download, generate a HTML file with a body that looks like this:
<iframe src="http://filetodownload.exe" style="display:none"></iframe>
Store this file in a temporary folder, e.g. C:\tmp\filetodownload.html
In your "master" generated HTML file, replace the iframe source with this intermediate file:
<iframe src="C:\tmp\filetodownload.html"
onload="downloadsInfo['http://filetodownload.exe']='Status: Download Started!';"
style="display:none"></iframe>
That may do the trick. But following IE's tradition, this could or could not work depending on the case...
If it does not work, some solutions that have proved useful include:
Put the onload handler in a function, and write in the definition of the iframe: onload="return theonloadfunction()" (even if the function does not return anything)
Instead of using the onload attribute, attach the event handler in javascript, like so:
iframe = document.getElementById("theiframeid")
iframe.attachEvent("onload", theonloadfunction);`
Note that attachEvent is for IE only. If you want to support other browsers you will have to detect it and use addEventListener for the non-IE cases.
Finally, you may try combinations of two or more of these solutions :)
<html>
<head>
<meta content = 'text/html;charset=utf-8' http-equiv = 'Content-Type'>
<meta content = 'utf-8' http-equiv = 'encoding'>
<script>
/*
First, I removed the setInterval(). Since you rely on the onload property we can aswell just check it on each onload.
Second, I changed your downloadsInfo to an object array.
Also be aware while testing, that some browsers cache your cancel/block choice and do not reask again for the same url.
Additionally firefox does not fire on frame downloads.
Furthermore the alert in your test might not show for overlapping or setting reasons.
*/
var downloadsInfo = [
{url: "http://download-installer.cdn.mozilla.net/pub/firefox/releases/26.0/win32/en-US/Firefox%20Setup%2026.0.exe", Status: "Connecting"},
{url: "http://download.piriform.com/ccsetup410.exe", Status: "Connecting"}
];
//IE has a problem in sometimes merely firing the onload propery once, which we bypass by dynamically creating them
//It is also less limited.
function iframeConnect(){
for(var i=0, j=downloadsInfo.length; i<j; i++){
var tF = document.createElement('iframe');
tF.arrayIndex = i; //For convenience
tF.style.display = 'none';
//Normal load event, working in ie8-11, chrome, safari
tF.onload = function(){
iframeExecuted(this.arrayIndex);
};
//Workaround for firefox, opera and some ie9
tF.addEventListener('DOMSubtreeModified', function(){
iframeExecuted(this.arrayIndex);
}, false);
document.body.appendChild(tF);
tF.src = downloadsInfo[i].url;
}
}
function iframeExecuted(i){
downloadsInfo[i].Status = 'Executed';
var tStatus = iframeFinished();
var tE = document.querySelector('h3');
if (tStatus.Done) tE.innerHTML = 'Finished'
else tE.innerHTML = 'Processed ' + tStatus.Processed + ' of ' + tStatus.Started;
}
function iframeFinished(){
for(var i=0, j=downloadsInfo.length; i<j; i++){
if (downloadsInfo[i].Status != 'Executed') break;
}
//Note that the Processed value is not accurate, yet it solves is testing purpose.
return {Done: (i == j), Processed: i, Started: j}
}
</script>
</head>
<body onload = 'iframeConnect()'>
<h3>Please wait for your downloads to start and do not reload this site.</h3>
</body>
</html>

Check browser width and execute a Javascript file and override another Javascript

There is an HTML file with many embedded YouTube videos.Page load times were slow so I decided to use this JS file to force the page load an image instead of iframe, until the user clicks on it. http://www.skipser.com/p/2/p/youtube-video-embed-like-google-plus.html
CSS checks if the visitor uses mobile and optimizes the layout for mobile.I modified the above mentioned JS script to show smaller thumbnails so it will work better on mobile(no need to scroll horizontally).I have 2 version of that JS script now.
The goal: Check if visitor uses desktop.If yes, execute the regular gplus-youtubeembed.js.If visitor uses mobile then execute gplus-youtubeembed-mobile.js
This was the original HTML.It would only load the desktop version of JS.As a result, mobile visitors would see a very large video thumbnail.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width; initial-scale=1.0; user-scalable=yes">
<script src=gplus-youtubeembed.js></script>
<link rel=stylesheet type="text/css" href="css/style.css" media=screen />
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<script>optimizeYouTubeEmbeds()</script> <!--needed to load image instead of iframe-->
</body>
</html>
Then I used this method http://www.coalmarch.com/blog/how-to-execute-javascript-based-on-screen-size-using-jquery
if ( $(window).width() > 700) {
//added the content of gplus-youtubeembed.js here
}
else {
//added the content of gplus-youtubeembed-mobile.js here
}
I named that gplus-youtubeembed-combine.js and replaced gplus-youtubeembed.js with gplus-youtubeembed-combined.js , in the HTML doc.
The outcome: The only JS that gets executed is the mobile version.Desktop visitors see small thumbnails.Everyting works fine in mobile.Why doesn't the gplus-youtubeembed-combined.js work properly ? It's supposed to detect if the screen width is over 700 and execute the gplus-youtubeembed.js file but it doesn't.Any help is appreciated.Thanks !
From what I understand
if ( $(window).width() > 700) {
//added the content of gplus-youtubeembed.js here
}
else {
//added the content of gplus-youtubeembed-mobile.js here
}
works only when a window is first loaded or refreshed. Try changing the size of your window and refresh your page. If the code works, you'll need something to reload the script or the page on resize.
Something like this:
$(window).resize(function() {
// add the stuff here to execute the your slider again;
});
or this might do the trick:
<script>
function refresh() { location.reload(); }
</script>
<body onresize="refresh()">
I'm no expert but I had similar issue just a few minutes ago. Hope I helped.
Here is a little more detail on the second code that you asked for.
I'm only sharing with you what I'm learning as I go. I'm a real noob. Having the same problem as you but with a different snippet.
$(document).ready(function(){
$(window).on('resize', function(){
if ($(window).width() > 700) {
// code here
} esle {
// code here
}
});
});
But you said refreshing your page didn't make the JS run. Which means this method might not help you. Have you checked to make sure both JS run and work regardless of page width? Maybe test each JS individually to make sure the mobile version is good.
Sorry if I can't be much help to you. I'm learning as I try to solve my own issues. Thought yours was close to the issue I was having.
Problem was fixed.When I copy/pasted two JS files into the if/else statement, something broke the "if" statement so "else" was always being executed.I confirmed this by swapping the mobile and desktop versions and changing ">" to "<".In that case only desktop version would load.
Instead of copy/pasting the entire JS files into else/if, I left the common part out and added only the portion that was different in desktop/mobile version.Sounds simple, but it didn't come to my mind at the beginning.
The author of the original JS did not provide the mobile friendly version of the JS so people who use that code on their website might benefit from this post.One issue with the below code is that on mobile version, the image doesn't have a play button.It only has a thumbnail so make sure the visitor knows it's a video.This can be fixed by further tweaking the code but that's another topic.
Working version.
gplus-youtubeembedded-combine.js
// gplus-youtubeembed - Makes embedded YouTube video iframes Google+ style to improve page loading speed.
// Copyright (c) 2013 by Arun - http://www.skipser.com
// Licensed under the GNU LGPL license: http://www.gnu.org/copyleft/lesser.html
// For usage details, read - http://www.skipser.com/510
// Call this function at the end of the closing </body> tag.
function optimizeYouTubeEmbeds() {
// Get all iframes
var frames = document.getElementsByTagName( 'iframe' );
// Loop through each iframe in the page.
for ( var i = 0; i < frames.length; i++ ) {
// Find out youtube embed iframes.
if ( frames[ i ].src && frames[ i ].src.length > 0 && frames[ i ].src.match(/http(s)?:\/\/www\.youtube\.com/)) {
// For Youtube iframe, extract src and id.
var src=frames[i].src;
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
var id=(src.match(p) ? RegExp.$1 : false);
if(id == false) { continue;}
// Get width and height.
var w=frames[i].width;
var h=frames[i].height;
if(src == '' || w=='' || h=='') {continue;}
if ( $(window).width() > 700) {
// Thease are to position the play button centrally.
var pw=Math.ceil(w/2-38.5);
var ph=Math.ceil(h/2+38.5);
// The image+button overlay code.
var code='<div alt="For this Google+ like YouTube trick, please see http://www.skipser.com/510" style="width:'+w+'px; height:'+h+'px; margin:0 auto"><img src="http://i.ytimg.com/vi/'+id+'/hqdefault.jpg" style="width:'+w+'px; height:'+h+'px;" /><div style="background: url(\'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAE0AAABNCAYAAADjCemwAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABgtJREFUeNrtXE1IJEcUFuYgHhZZAzOQwKLsaeY4MuCisLNkMUYM+TtmQwgYQSEg8RCIBAMBSYIQPCgEEiEYISZIgrhzCRLYg+BBMiiDGCHGH4xGETH4O85M+huql7Knuqe7urq7ercePAZnuqtefXZVvfe911VToyRUUqdpVNMmTROaJjVt0bRN0/uapslnG/k+Sa5rIvfVPQ8gRTSNaRrX9B4Bxa3eI+3FSPvPjLxAnpAbA+7s7HxrcnLyk8XFxe82NjZ+Ozw8XDk9Pd29urr6r1Ao5EulUhGf+Bvf43dch+txH+5ngJgg/YVWXtI0RQ9qbGzso1wu99PJyclfJQGCdtAe2jWAlyL9h0ZeJGtQeQC9vb2Pstns1NnZ2X7JQ0H76Af9UeC1EHukldtksS4bPDw83Le5uTlfCkDQL/qnwEsS+6SSu/SThbWnJIHADsOTd1cGsG5p2qwbhUXayaCOj4//XFtbm52fn/96fHx8oK+v793W1tbXGhoaHkYikQf4xN/4Hr/jOlyP+5z0A7so4JqJ3YFITPenBgcHP8DuZm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mRNC+XuSZjgX0QG9052z9D5aYYivXQQflpoIoKLi4tDsBFesb1OIgLpY09MxVwu97PXPJuT2FNqlgMMx8DAwPt+0ENOWA4p+TRMRT8TL075NKmYW3j1y8vLP8bj8Vf9pLudMrfS5Aj29/eXgsrE8+QIAs1GgeaZnp7+LKgUHm82KpC8J6ZiNpv9we+pKCrv6XuGHUUxPT09j2QoTeDNsPtWy6EZuDc1NfWp7CWldms5PK0a0qbixdLS0veyFL6IqhryrD5td3d3IaiSAz/q01QlJEclpKq55ay5VdXdHNXdEPUeAaeoN1Y4Rb0bxSHqLTxOUe97cop6s5hT1DvsboFTpyVwTlV1LofzzUGdAMPpjqizhtxEDjXqVCuuWFWdn8Yp6qQ+F6LOhHQh6vRRF6LOuRUg6kTl50n+B4KhcERZo7nRAAAAAElFTkSuQmCC\') no-repeat scroll 0 0 transparent;height: 77px;width: 77px; position:relative; margin-left:'+pw+'px; margin-top:-'+ph+'px;z-index:5;"></div></div>';
}
else {
var pw=Math.ceil(w/7.5-1.5);
var ph=Math.ceil(h/4.7+10);
var code='<div alt="For this Google+ like YouTube trick, please see http://www.skipser.com/510" style="max-width:100%;height:auto; margin:0 auto"><img src="http://i.ytimg.com/vi/'+id+'/hqdefault.jpg" style="max-width:100%;height:auto;" /> <div style="background: url(\'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAE0AAABNCAYAAADjCemwAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAABgtJREFUeNrtXE1IJEcUFuYgHhZZAzOQwKLsaeY4MuCisLNkMUYM+TtmQwgYQSEg8RCIBAMBSYIQPCgEEiEYISZIgrhzCRLYg+BBMiiDGCHGH4xGETH4O85M+huql7Knuqe7urq7ercePAZnuqtefXZVvfe911VToyRUUqdpVNMmTROaJjVt0bRN0/uapslnG/k+Sa5rIvfVPQ8gRTSNaRrX9B4Bxa3eI+3FSPvPjLxAnpAbA+7s7HxrcnLyk8XFxe82NjZ+Ozw8XDk9Pd29urr6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ARfye7SC+2cF58gzygAacY6LYFq7urre9go0jNciiG+q8M9YsaYovkxk5txL55jl6FKxaKKCBmLxZshsywYa7UfNzc19IZJxwXgteLZkBauBOjDjDSgJkBU0et0dHR3tF2EnxmtsH7iwWA+UaKZRQGe8AbUUsoOmy87OzhO3zjHGa2wXuJDf22jQytkmUoF4Q1CEEhbQRDjHGC9jA8pT2aqnog+sInkiKpj2CzTssNgB0+n06zx2YrysEI+65tl60hD4Dw0N9bix08mTFuo1DSFXJpP5UsQu6mRNC+XuSZjgX0QG9052z9D5aYYivXQQflpoIoKLi4tDsBFesb1OIgLpY09MxVwu97PXPJuT2FNqlgMMx8DAwPt+0ENOWA4p+TRMRT8TL075NKmYW3j1y8vLP8bj8Vf9pLudMrfS5Aj29/eXgsrE8+QIAs1GgeaZnp7+LKgUHm82KpC8J6ZiNpv9we+pKCrv6XuGHUUxPT09j2QoTeDNsPtWy6EZuDc1NfWp7CWldms5PK0a0qbixdLS0veyFL6IqhryrD5td3d3IaiSAz/q01QlJEclpKq55ay5VdXdHNXdEPUeAaeoN1Y4Rb0bxSHqLTxOUe97cop6s5hT1DvsboFTpyVwTlV1LofzzUGdAMPpjqizhtxEDjXqVCuuWFWdn8Yp6qQ+F6LOhHQh6vRRF6LOuRUg6kTl50n+B4KhcERZo7nRAAAAAElFTkSuQmCC\') no-repeat scroll 0 0 transparent;height: 77px;width: 77px; position:relative; margin-left:'+pw+'px; margin-top:-'+ph+'px;z-index:5;"></div><br><br><br></div>';
}
// Replace the iframe with a the image+button code.
var div = document.createElement('div');
div.innerHTML=code;
div=div.firstChild;
frames[i].parentNode.replaceChild(div, frames[i]);
i--;
}
}
}
// Replace preview image of a video with it's iframe.
function LoadYoutubeVidOnPreviewClick(id,w ,h) {
var code='<iframe src="https://www.youtube.com/embed/'+id+'/?autoplay=1&autohide=1&border=0&wmode=opaque&enablejsapi=1" width="'+w+'" height="'+h+'" frameborder=0 allowfullscreen style="border:1px solid #ccc;" ></iframe>';
var iframe = document.createElement('div');
iframe.innerHTML=code;
iframe=iframe.firstChild;
var div=document.getElementById("skipser-youtubevid-"+id);
div.parentNode.replaceChild( iframe, div)
}
I've implemented the code here (it's my website) http://www.veryslowpc.com/security-measures.html
The outcome: in order to reduce page load times, embedded video iframes don't load until the user clicks on them, and the thumbnails are within page width when viewed on mobile.
Thank you for suggestions.
EDIT: The code should display the play button now.

How can a site instantly detect that javascript has been disabled?

Normally, when a page is loaded, and the browser has Javascript disabled, we use the <noscript> tag to write something like a warning and tell the client to enable Javascript. However, Facebook, even after you load the page with JS enabled, the moment it's disabled you get a notification. How can I do something like this?
UPDATE : This mechanism is no longer available in Facebook, but it was before, I was too late in asking this question, but if any answer is found, I would really appreciate it.
What I have tried
I thought about having a segment inside my page which keeps checking if Javascript is disabled, if yes, show the contents of <noscript>.
To Achieve this, I created a page CheckJS.html.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0">
</head>
<body>
<noscript>
JS is disabled!
</noscript>
</body>
</html>
This page will keep on refreshing, when JS is disabled, JS is disabled! will appear.
To add this page inside my original page. I tried the following:
1- .load()
I used JQuery to .load('CheckJS.html') inside a div. However, it seems that .load() only loads the contents of the <body> of CheckJS.html. Means the <head> element and what's inside it will not be loaded inside the div.
2- iframe
After some searching, I found that the only possible way to load a FULL html page including <head> is to use an <iframe>.
<iframe src="CheckJS.html"></iframe>
However, the <meta http-equiv="refresh" content="0"> of CheckJS.html affects the parent page, the original page itself started refreshing.
If we are able to use this <iframe> without forcing the original page to refresh, then this could be a solution, but even if this solution is found, I feel its more of a trick rather than a real solution.
UPDATE
Antony 's answer proved that I was wrong about that the iframe refreshes the original page, the browser shows that its refreshing but actually its not, if this is it, then Javascript can be avoided, the CheckJS.html that I provided does the job, and even better, the <noscript> will be hidden when JS is re-enabled. Still this whole iframe approach isn't so user friendly (could freeze the browser), unless refresh occurs every 10 seconds or so, which isn't an instant detection.
CSS Solution
See DEMO. Also available as a JS library.
Stop the CSS animation by continuously replacing the element with JavaScript. Once JavaScript is disabled, the CSS animation kicks in and displays a message.
#keyframes Browser compatibility: Chrome, Firefox 5.0+, IE 10+, Opera 12+, Safari 4.0+
<style>
.nojs_init {
position: relative;
animation:nojs-animation 0.2s step-end;
-moz-animation:nojs-animation 0.2s step-end; /* Firefox */
-webkit-animation:nojs-animation 0.2s step-end; /* Safari and Chrome */
-o-animation:nojs-animation 0.2s step-end; /* Opera */
}
#keyframes nojs-animation
{
from {visibility:hidden;opacity:0;}
to {visibility:visible;opacity:1;}
}
#-moz-keyframes nojs-animation /* Firefox */
{
from {visibility:hidden;opacity:0;}
to {visibility:visible;opacity:1;}
}
#-webkit-keyframes nojs-animation /* Safari and Chrome */
{
from {visibility:hidden;opacity:0;}
to {visibility:visible;opacity:1;}
}
#-o-keyframes nojs-animation /* Opera */
{
from {visibility:hidden;opacity:0;}
to {visibility:visible;opacity:1;}
}
</style>
<body>
<div id="content"></div>
<div id="nojs" class="nojs_init"><noscript>JavaScript is <span style="font-weight:bold;">disabled</span>.</noscript></div>
</body>
<script>
document.getElementById("content").innerHTML = 'JavaScript is <span style="font-weight:bold;">enabled</span>. Try disabling JavaScript now.';
var elm = document.getElementById("nojs"),
animation = false,
animationstring = 'animation',
keyframeprefix = '',
domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
pfx = '';
if( elm.style.animationName ) { animation = true; }
if( animation === false ) {
for( var i = 0; i < domPrefixes.length; i++ ) {
if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
pfx = domPrefixes[ i ];
animationstring = pfx + 'Animation';
keyframeprefix = '-' + pfx.toLowerCase() + '-';
animation = true;
break;
}
}
}
// Continuously replace element
function jsdetect() {
var elm = document.getElementById("nojs");
var newone = elm.cloneNode(true);
elm.parentNode.replaceChild(newone, elm);
}
// Only apply to browsers that support animation
if (animation) {
elm.innerHTML = 'JavaScript is <span style="font-weight:bold;">disabled</span>.';
setInterval(jsdetect, 0);
}
</script>
Hrm, I think it depends on the browser. HTML5 supports <noscript> in the HEAD element, so you might try something like this:
<style>
.noscriptMessage {
display: none;
}
</style>
<noscript>
<style>
.noscriptMessage {
display: block
}
</style>
</noscript>
<body>
<div class=".noscriptMessage">Foo bar baz</div>
...
</body>
Spec: http://dev.w3.org/html5/markup/noscript.html
From the spec:
Permitted contents: Zero or more of: one link element, or one meta
http-equiv=default-style element, or one meta http-equiv=refresh
element, or one style element
Edit: hey peeps, SO does the very same! Just try turning off JS now.
What about javascript code that continuously postpones a http-equiv=refresh (each time replacing the meta element?) As soon as javascript is turned off, the meta element is no longer replaced and the refresh will eventually take place. This is just a thought, I've no idea if meta element insertion is even possible.
I'd recommend looking into how this is done by HTML5 Boilerplate and Modernizr.
If you look at HTML5 Boilerplate's HTML, on line 7 you'll see the <html> tag is given a class of no-js. Then, when Modernizr's JavaScript runs, the first thing it does is remove the no-js class.
That done, you could apply CSS rules that only display content if the no-js class is present:
#no-script-message {
display: none;
}
.no-js #no-script-message {
display: block;
}
Expanding upon #JoshMock's answer, here is a simple approach (via Paul Irish) to detect if the client has JS enabled:
HTML
<html class="no-js">
<head>
<script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script>
This should be compatible with all browsers and is quite fast. Then you can hide/show elements in your css with .js and .no-js classes.
If you are doing any other feature detection, I would suggest using Modernizr with the html class="no-js" markup (modernizr will automatically add the js classes for you, along with css3 detection).
Actually, it is easier to detect if java-script is supported by the browser than the opposite.
Of course, this is in the case of 'a site instantly detect javascript'. Witch is the very first http-request <--> response from the browser to the server. You just 'cannot'. You would have to send another request to the server after determining browser capabilities.
Now, there is no way of checking if JavaScript is enabled from the server-side on the first request. So, if JavaScript is disabled, you have to do a postback, or redirect to a non JavaScript page, using what some other suggested (witch is not valid, but seems to work):
<head>
<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html"></noscript>
...
</head>
There are some 'browser capabilities' and browser 'plugins' that can be get with http request, so you would need a good 'server-side' script to meet your goal.
See browserhawk or quirksmode for some infos on a javascript to detect browser.
Also, there is a 'protected' question aboout how-to-detect-if-javascript-is-disabled

Categories

Resources