How to check browser's JavaScript is enabled or not - javascript

My application depends on JavaScript, I want to check the client browser's JavaScript is enabled or not and raise an alert message if its turned off.

There's actually a <noscript> tag that you can use to display the content contained inside when javascript is not available.
Something like:
<noscript>
<div>
You must enable javascript to continue.
</div>
</noscript>
The div just won't show if they have javascript, and it's pretty easy to tell if javascript IS working, no matter whether you need it to ping your server back to let it know, or use it to perform some more advanced functions.

Put the message in a <div> that's wrapped in a <noscript> tag. If JavaScript is disabled, the <div> will be rendered as part of the DOM; if script is enabled, the div won't be in the DOM.
For example, you can put the following immediately after the opening <body> tag, and style it through CSS to have red background to make it more prominent.
<noscript>
<div id="js-warning">
To be able to access all of our features, you need a browser that supports JavaScript, and it needs to be enabled.
</div>
</noscript>

"Raise an alert message if its turned off" is paradox, since if it is turned off, you cannot "do" anything programatically.
You can do it the other way 'round, however: make that message appear by default, and have JavaScript hide it if it is turned on (e.g. by setting a DIVs visibility to hidden),
or you rely on the standard compliance of the browser and use the <noscript> tag. Stuff inside the <noscript> gets shown if no javascript is enabled. BTW, make sure to set the type="text/javascript" attribute of the script tag.
See also http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.3

A browser may be "JavaScript capable" but that does not mean that JavaScript has not been disabled by the user or by an admin. There is no real way to determine this. Best practices dictate "Progressive Enhancement"; that is, you application needs to work without JavaScript first - then add the JavaScript functionality for those (most) that have it enabled.
http://www.alistapart.com/articles/progressiveenhancementwithjavascript/
http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/progressive-enhancement.shtml
Avoid hacky solutions to this and bear in mind that there are also accessibility issues for people with screen readers. <noscript> content only displays if JavaScript is disabled. Most screen reader users have JavaScript enabled, so they will see your inaccessible script rather than the <noscript> content.

Related

How to check Javascripts are disabled by proxy

I do not know weather there is any way to solve this or not, but I'm just asking it because I believe SO is a place of genius people. Anyways, we all know that if we use <noscript></noscript> tag within a HTML document and if any user who are viewing this page and have JavaScript disabled from their browser will see the no script message.
But what if JavaScript has been disabled by proxy? Many wifi networks needs to manually input some proxy to use internet and many of them disabled JS on that proxy from the proxy server. In this case if anybody visit the same page, the page will see that JavaScript has been enabled from browser, but disabled from proxy.
If there any way to check weather JavaScript has been disabled by any proxy(if using) and showing alert message for this? Also I will be glad if anybody can say that how to implement it with Wordpress and also without wordpress. :)
Thanks.
You can show the message by default and then remove or hide it with JavaScript, e.g.:
<div id="jsalert">JavaScript is disabled in your environment.</div>
<script>
(function() {
var elm = document.getElementById("jsalert");
elm.parentNode.removeChild(elm);
})();
</script>
<!-- Continue your content here -->
If script tags have been stripped by a proxy (which I'm fairly certain is very unusual; at least, I've never seen it), then of course the script won't be there to be run, and the div will show. If the script is present, it will remove the div.
By following the div with the script immediately (which is perfectly fine, no need for "DOM ready" stuff that will just delay things), the odds of the div "flashing" briefly on the page in the common case (where JavaScript is enabled and not stripped out) are very low. Not zero, but low.
If you believe the proxy doesn't strip out script tags but instead just blocks the downloads of JavaScript files (which would be dumb), you can change the above to use a JavaScript file, but beware that by doing that you either hold up the rendering of your page (if you use <script src="...">) or you increase (dramatically) the odds of the div "flashing" on the page briefly (if you load the script asynchronously).
This is just a specific use-case for a general practice called "progressive enhancement" (or sometimes "graceful degradation," but most people prefer the first). That's where you ensure that the page is presented correctly and usefully in the case where JavaScript is not available, and then use JavaScript to add behaviors to the page if JavaScript is enabled. In this case, the "useful" thing you're doing is saying that JavaScript isn't running for some reason, so it's a slightly different thing, but it's the same principle.

Checking if browser is javascript enabled or not

<noscript>
<div>
You must enable javascript to continue.
</div>
</noscript>
Ok this makes sense, but still, the contents after this element will be shown, of course in a bad way, but what I am looking for is this:
If javascript is NOT enabled, I want to show this alert message, and NOTHING ELSE, I don't want to give advice "It's better if you enabled Javascript", I want to FORCE, "You MUST ENABLED so you can Continue!", I don't wanna give access to my website if javascript is not enbaled, how can I do that?
Add a No-Javascript CSS class that hides everything else using CSS, and use Javascript to remove the class immediately (using an inline <script> block in that element).
<noscript>
<div style='position:fixed;left:0;top:0;width:100%;height:100%;background:#f55;z-index=1000">
You must enable javascript to continue.
</div>
</noscript>
Also, your question wanted to throw an alert.. Which is JavaScript. You basically asked "how can I execute JS when JS is disabled?". But this HTML alone will do the trick.

<noscript> or something else

I have a site that relies heavily on JavaScript and uses jQuery throughout.
I'm not going to attempt to make the site work for those who don't have JavaScript enabled.
However, I would like to show a banner at the top of the page which tells them the site is intended for use with JavaScript enabled and perhaps a modern browser, etc.
I was thinking of just putting a PHP include on all pages that contains a <noscript> with the banner inside that. Is this is good approach or is there a better way?
<noscript> is the way to go.
You should also provide links to other, better browsers in the <noscript> tag if you can detect that's a browser without JavaScript.
If you wish to be more drastic about it, start with the markup <body class="nojs"> and, onload remove that class with JavaScript.
You could then have body.nojs #wrapper { display: none; }, body.nojs #notice { display: block } in your CSS.
Maybe How to know and handle disabled JavaScript in the browser can help you.
That is definitely one alternative...
Another is to have the banner visible by default without using noscript and then a $().ready() which hides the banner for all JavaScript enabled browsers.

Detecting Javascript enabled? [duplicate]

There was a post this morning asking about how many people disable JavaScript. Then I began to wonder what techniques might be used to determine if the user has it disabled.
Does anyone know of some short/simple ways to detect if JavaScript is disabled? My intention is to give a warning that the site is not able to function properly without the browser having JS enabled.
Eventually I would want to redirect them to content that is able to work in the absence of JS, but I need this detection as a placeholder to start.
I'd like to add my .02 here. It's not 100% bulletproof, but I think it's good enough.
The problem, for me, with the preferred example of putting up some sort of "this site doesn't work so well without Javascript" message is that you then need to make sure that your site works okay without Javascript. And once you've started down that road, then you start realizing that the site should be bulletproof with JS turned off, and that's a whole big chunk of additional work.
So, what you really want is a "redirection" to a page that says "turn on JS, silly". But, of course, you can't reliably do meta redirections. So, here's the suggestion:
<noscript>
<style type="text/css">
.pagecontainer {display:none;}
</style>
<div class="noscriptmsg">
You don't have javascript enabled. Good luck with that.
</div>
</noscript>
...where all of the content in your site is wrapped with a div of class "pagecontainer". The CSS inside the noscript tag will then hide all of your page content, and instead display whatever "no JS" message you want to show. This is actually what Gmail appears to do...and if it's good enough for Google, it's good enough for my little site.
I assume you're trying to decide whether or not to deliver JavaScript-enhanced content. The best implementations degrade cleanly, so that the site will still operate without JavaScript. I also assume that you mean server-side detection, rather than using the <noscript> element for an unexplained reason.
There is no good way to perform server-side JavaScript detection. As an alternative it is possible to set a cookie using JavaScript, and then test for that cookie using server-side scripting upon subsequent page views. However this would be unsuitable for deciding what content to deliver, as it would not distinguish visitors without the cookie from new visitors or from visitors who did not accept the JavaScript set cookie.
noscript blocks are executed when JavaScript is disabled, and are typically used to display alternative content to that you've generated in JavaScript, e.g.
<script type="javascript">
... construction of ajaxy-link, setting of "js-enabled" cookie flag, etc..
</script>
<noscript>
Next Page
</noscript>
Users without js will get the next_page link - you can add parameters here so that you know on the next page whether they've come via a JS/non-JS link, or attempt to set a cookie via JS, the absence of which implies JS is disabled. Both of these examples are fairly trivial and open to manipulation, but you get the idea.
If you want a purely statistical idea of how many of your users have javascript disabled, you could do something like:
<noscript>
<img src="no_js.gif" alt="Javascript not enabled" />
</noscript>
then check your access logs to see how many times this image has been hit. A slightly crude solution, but it'll give you a good idea percentage-wise for your user base.
The above approach (image tracking) won't work well for text-only browsers or those that don't support js at all, so if your userbase swings primarily towards that area, this mightn't be the best approach.
This is what worked for me: it redirects a visitor if javascript is disabled
<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html" /></noscript>
I'd suggest you go the other way around by writing unobtrusive JavaScript.
Make the features of your project work for users with JavaScript disabled, and when you're done, implement your JavaScript UI-enhancements.
https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
If your use case is that you have a form (e.g., a login form) and your server-side script needs to know if the user has JavaScript enabled, you can do something like this:
<form onsubmit="this.js_enabled.value=1;return true;">
<input type="hidden" name="js_enabled" value="0">
<input type="submit" value="go">
</form>
This will change the value of js_enabled to 1 before submitting the form. If your server-side script gets a 0, no JS. If it gets a 1, JS!
<noscript> isn't even necessary, and not to mention not supported in XHTML.
Working Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
<title>My website</title>
<style>
#site {
display: none;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js "></script>
<script>
$(document).ready(function() {
$("#noJS").hide();
$("#site").show();
});
</script>
</head>
<body>
<div id="noJS">Please enable JavaScript...</div>
<div id="site">JavaScript dependent content here...</div>
</body>
</html>
In this example, if JavaScript is enabled, then you see the site. If not, then you see the "Please enable JavaScript" message. The best way to test if JavaScript is enabled, is to simply try and use JavaScript! If it works, it's enabled, if not, then it's not...
Use a .no-js class on the body and create non javascript styles based on .no-js parent class.
If javascript is disabled you will get all the non javascript styles,
if there is JS support the .no-js class will be replaced giving you all the styles as usual.
document.body.className = document.body.className.replace("no-js","js");
trick used in HTML5 boilerplate http://html5boilerplate.com/ through modernizr but you can use one line of javascript to replace the classes
noscript tags are okay but why have extra stuff in your html when it can be done with css
just a bit tough but (hairbo gave me the idea)
CSS:
.pagecontainer {
display: none;
}
JS:
function load() {
document.getElementById('noscriptmsg').style.display = "none";
document.getElementById('load').style.display = "block";
/* rest of js*/
}
HTML:
<body onload="load();">
<div class="pagecontainer" id="load">
Page loading....
</div>
<div id="noscriptmsg">
You don't have javascript enabled. Good luck with that.
</div>
</body>
would work in any case right?
even if the noscript tag is unsupported (only some css required)
any one knows a non css solution?
You can use a simple JS snippet to set the value of a hidden field. When posted back you know if JS was enabled or not.
Or you can try to open a popup window that you close rapidly (but that might be visible).
Also you have the NOSCRIPT tag that you can use to show text for browsers with JS disabled.
You'll want to take a look at the noscript tag.
<script type="text/javascript">
...some javascript script to insert data...
</script>
<noscript>
<p>Access the data.</p>
</noscript>
Because I always want to give the browser something worthwhile to look at I often use this trick:
First, any portion of a page that needs JavaScript to run properly (including passive HTML elements that get modified through getElementById calls etc.) are designed to be usable as-is with the assumption that there ISN'T javaScript available. (designed as if it wasn't there)
Any elements that would require JavaScript, I place inside a tag something like:
<span name="jsOnly" style="display: none;"></span>
Then at the beginning of my document, I use .onload or document.ready within a loop of getElementsByName('jsOnly') to set the .style.display = ""; turning the JS dependent elements back on. That way, non-JS browsers don't ever have to see the JS dependent portions of the site, and if they have it, it appears immediately when it's ready.
Once you are used to this method, it's fairly easy to hybridize your code to handle both situations, although I am only now experimenting with the noscript tag and expect it will have some additional advantages.
The noscript tag works well, but will require each additional page request to continue serving useless JS files, since essentially noscript is a client side check.
You could set a cookie with JS, but as someone else pointed out, this could fail. Ideally, you'd like to be able to detect JS client side, and without using cookies, set a session server side for that user that indicates is JS is enabled.
A possibility is to dynamically add a 1x1 image using JavaScript where the src attribute is actually a server side script. All this script does is saves to the current user session that JS is enabled ($_SESSION['js_enabled']). You can then output a 1x1 blank image back to the browser. The script won't run for users who have JS disabled, and hence the $_SESSION['js_enabled'] won't be set. Then for further pages served to this user, you can decide whether to include all of your external JS files, but you'll always want to include the check, since some of your users might be using the NoScript Firefox add-on or have JS disabled temporarily for some other reason.
You'll probably want to include this check somewhere close to the end of your page so that the additional HTTP request doesn't slow down the rendering of your page.
Add this to the HEAD tag of each page.
<noscript>
<meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
</noscript>
So you have:
<head>
<noscript>
<meta http-equiv="refresh" runat="server" id="mtaJSCheck" content="0;logon.aspx" />
</noscript>
</head>
With thanks to Jay.
A common solution is to the meta tag in conjunction with noscript to refresh the page and notify the server when JavaScript is disabled, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<noscript>
<meta http-equiv="refresh" content="0; /?javascript=false">
</noscript>
<meta charset="UTF-8"/>
<title></title>
</head>
</html>
In the above example when JavaScript is disabled the browser will redirect to the home page of the web site in 0 seconds. In addition it will also send the parameter javascript=false to the server.
A server side script such as node.js or PHP can then parse the parameter and come to know that JavaScript is disabled. It can then send a special non-JavaScript version of the web site to the client.
This is the "cleanest" solution id use:
<noscript>
<style>
body *{ /*hides all elements inside the body*/
display: none;
}
h1{ /* even if this h1 is inside head tags it will be first hidden, so we have to display it again after all body elements are hidden*/
display: block;
}
</style>
<h1>JavaScript is not enabled, please check your browser settings.</h1>
</noscript>
If javascript is disabled your client-side code won't run anyway, so I assume you mean you want that info available server-side. In that case, noscript is less helpful. Instead, I'd have a hidden input and use javascript to fill in a value. After your next request or postback, if the value is there you know javascript is turned on.
Be careful of things like noscript, where the first request may show javascript disabled, but future requests turn it on.
You might, for instance, use something like document.location = 'java_page.html' to redirect the browser to a new, script-laden page. Failure to redirect implies that JavaScript is unavailable, in which case you can either resort to CGI ro utines or insert appropriate code between the tags. (NOTE: NOSCRIPT is only available in Netscape Navigator 3.0 and up.)
credit
http://www.intranetjournal.com/faqs/jsfaq/how12.html
A technique I've used in the past is to use JavaScript to write a session cookie that simply acts as a flag to say that JavaScript is enabled. Then the server-side code looks for this cookie and if it's not found takes action as appropriate. Of course this technique does rely on cookies being enabled!
I think you could insert an image tag into a noscript tag and look at the stats how many times your site and how often this image has been loaded.
People have already posted examples that are good options for detection, but based on your requirement of "give warning that the site is not able to function properly without the browser having JS enabled". You basically add an element that appears somehow on the page, for example the 'pop-ups' on Stack Overflow when you earn a badge, with an appropriate message, then remove this with some Javascript that runs as soon as the page is loaded (and I mean the DOM, not the whole page).
code inside <noscript> tags will be executed when there is no js enabled in browser.
we can use noscript tags to display msg to turn on JS as below.
<noscript>
<h1 style="text-align: center;">
To view this page properly, please
enable JavaScript and reload the page
</h1>
</noscript>
while keeping our website content inside body as hidden. as below
<body>
<div id="main_body" style="display: none;">
website content.
</div>
</body>
now if JS is turned on you can just make the content inside your main_body visible as below
<script type="text/javascript">
document.getElementById("main_body").style.display="block";
</script>
Why don't you just put a hijacked onClick() event handler that will fire only when JS is enabled, and use this to append a parameter (js=true) to the clicked/selected URL (you could also detect a drop down list and change the value- of add a hidden form field). So now when the server sees this parameter (js=true) it knows that JS is enabled and then do your fancy logic server-side.
The down side to this is that the first time a users comes to your site, bookmark, URL, search engine generated URL- you will need to detect that this is a new user so don't look for the NVP appended into the URL, and the server would have to wait for the next click to determine the user is JS enabled/disabled. Also, another downside is that the URL will end up on the browser URL and if this user then bookmarks this URL it will have the js=true NVP, even if the user does not have JS enabled, though on the next click the server would be wise to knowing whether the user still had JS enabled or not. Sigh.. this is fun...
To force users to enable JavaScripts, I set 'href' attribute of each link to the same document, which notifies user to enable JavaScripts or download Firefox (if they don't know how to enable JavaScripts). I stored actual link url to the 'name' attribute of links and defined a global onclick event that reads 'name' attribute and redirects the page there.
This works well for my user-base, though a bit fascist ;).
You don't detect whether the user has javascript disabled (server side or client). Instead, you assume that javascript is disabled and build your webpage with javascript disabled. This obviates the need for noscript, which you should avoid using anyway because it doesn't work quite right and is unnecessary.
For example, just build your site to say <div id="nojs">This website doesn't work without JS</div>
Then, your script will simply do document.getElementById('nojs').style.display = 'none'; and go about its normal JS business.
Check for cookies using a pure server side solution i have introduced here then check for javascript by dropping a cookie using Jquery.Cookie and then check for cookie this way u check for both cookies and javascript
In some cases, doing it backwards could be sufficient. Add a class using javascript:
// Jquery
$('body').addClass('js-enabled');
/* CSS */
.menu-mobile {display:none;}
body.js-enabled .menu-mobile {display:block;}
This could create maintenance issues on anything complex, but it's a simple fix for some things. Rather than trying to detect when it's not loaded, just style according to when it is loaded.
I would like to add my solution to get reliable statistics on how many real users visit my site with javascript disabled over the total users. The check is done one time only per session with these benefits:
Users visiting 100 pages or just 1 are counted 1 each. This allows to focus on single users, not pages.
Does not break page flow, structure or semantic in anyway
Could logs user agent. This allow to exclude bots from statistics, such as google bot and bing bot which usually have JS disabled! Could also log IP, time etc...
Just one check per session (minimal overload)
My code uses PHP, mysql and jquery with ajax but could be adapted to other languanges:
Create a table in your DB like this one:
CREATE TABLE IF NOT EXISTS `log_JS` (
`logJS_id` int(11) NOT NULL AUTO_INCREMENT,
`data_ins` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`session_id` varchar(50) NOT NULL,
`JS_ON` tinyint(1) NOT NULL DEFAULT '0',
`agent` varchar(255) DEFAULT NULL,
PRIMARY KEY (`logJS_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Add this to every page after using session_start() or equivalent (jquery required):
<? if (!isset($_SESSION["JSTest"]))
{
mysql_query("INSERT INTO log_JS (session_id, agent) VALUES ('" . mysql_real_escape_string(session_id()) . "', '" . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']). "')");
$_SESSION["JSTest"] = 1; // One time per session
?>
<script type="text/javascript">
$(document).ready(function() { $.get('JSOK.php'); });
</script>
<?
}
?>
Create the page JSOK.php like this:
<?
include_once("[DB connection file].php");
mysql_query("UPDATE log_JS SET JS_ON = 1 WHERE session_id = '" . mysql_real_escape_string(session_id()) . "'");
I've figured out another approach using css and javascript itself.
This is just to start tinkering with classes and ids.
The CSS snippet:
1. Create a css ID rule, and name it #jsDis.
2. Use the "content" property to generate a text after the BODY element. (You can style this as you wish).
3 Create a 2nd css ID rule and name it #jsEn, and stylize it. (for the sake of simplicity, I gave to my #jsEn rule a different background color.
<style>
#jsDis:after {
content:"Javascript is Disable. Please turn it ON!";
font:bold 11px Verdana;
color:#FF0000;
}
#jsEn {
background-color:#dedede;
}
#jsEn:after {
content:"Javascript is Enable. Well Done!";
font:bold 11px Verdana;
color:#333333;
}
</style>
The JavaScript snippet:
1. Create a function.
2. Grab the BODY ID with getElementById and assign it to a variable.
3. Using the JS function 'setAttribute', change the value of the ID attribute of the BODY element.
<script>
function jsOn() {
var chgID = document.getElementById('jsDis');
chgID.setAttribute('id', 'jsEn');
}
</script>
The HTML part.
1. Name the BODY element attribute with the ID of #jsDis.
2. Add the onLoad event with the function name. (jsOn()).
<body id="jsDis" onLoad="jsOn()">
Because of the BODY tag has been given the ID of #jsDis:
- If Javascript is enable, it will change by himself the attribute of the BODY tag.
- If Javascript is disable, it will show the css 'content:' rule text.
You can play around with a #wrapper container, or with any DIV that use JS.
Hope this helps to get the idea.
Detect it in what? JavaScript? That would be impossible. If you just want it for logging purposes, you could use some sort of tracking scheme, where each page has JavaScript that will make a request for a special resource (probably a very small gif or similar). That way you can just take the difference between unique page requests and requests for your tracking file.

Shouldn't we use <noscript> element?

I found some good cons here:
The noscript element only detects whether the browser has JavaScript enabled or not. If JavaScript is disabled in the Firewall rather than in the browser then the JavaScript will not run and the content of the noscript element will not be displayed.
Many scripts are dependent on a specific feature or features of the language being supported in order for them to be able to run (for example document.getElementById). Where the required features are not supported the JavaScript is unable to run but since JavaScript itself is supported the noscript content will not be displayed.
The most useful place to use the noscript element is in the head of the page where it would be able to selectively determine what stylesheet and meta elements get applied to the page as the page is loading rather than having to wait until the page is loaded. Unfortunately the noscript element is only valid within the body of the page and so cannot be used in the head.
The noscript element is a block level element and therefore can only be used to display entire blocks of content when JavaScript is disabled. It cannot be used inline.
Ideally, web pages should use HTML for the content, CSS for the appearance, and JavaScript for the behavior. Using the noscript element is applying a behavior from within the HTML rather than applying it from JavaScript.
Source: http://javascript.about.com/od/reference/a/noscriptnomore.htm
I very much agree on last point. Is there a way to make and add an external <noscript> file? Should we place <noscript> in the <head>?
It's better to have the default be non-javascript, and then let a javascript code overwrite with a javascript enabled page. Doesn't have to be much. Can just be a display:none; block, which is then set to display:block; by javascript, and vice versa for the non-js page.
After pondering for many days and changing my code back and forth, I think I have clearer picture now and would like to share my two cents worth on the subject before I forget.
<div id='noscript'>show non-js content</div>
<script>document.getElementById('noscript').style.display='none';</script>
<script id='required script'>show js content</script>
vs
<noscript>show non-js content</noscript>
<script id='required script'>//show js content</script>
Depending on the situation, there are three cases for consideration:
Case 1 - If required script is inline
JavaScript disabled
Content in <noscript> element appears immediately, non-js content is
shown
Content in <div> element appears immediately, non-js content is shown
JavaScript enabled
Content in <noscript> element does not appear at all, js content shown
Content in <div> element may momentarily appear before being hidden, js
content shown
For this case, using <noscript> element is advantageous.
Case 2 - If required script is from external (third-party) source, but hiding of <div> element is done with inline script
JavaScript disabled
Content in <noscript> element appears immediately, non-js content is
shown
Content in <div> element appears immediately, non-js content is shown
JavaScript enabled but required script is blocked
Content in <noscript> element does not appear at all, nothing is shown!
Content in <div> element may momentarily appear before being hidden, nothing is shown!
JavaScript enabled and required script is received
Content in <noscript> element does not appear at all, js content shown
Content in <div> element may momentarily appear before being hidden, js
content shown
For this case, using <noscript> element is advantageous.
Case 3 - If required script hides the <div> element
JavaScript disabled
Content in <noscript> element appears immediately, non-js content is
shown
Content in <div> element appears immediately, non-js content is shown
JavaScript enabled but required script is blocked
Content in <noscript> element does not appear at all, nothing is shown!
Content in <div> element appears, non-js content is shown
JavaScript enabled and required script is received
Content in <noscript> element does not appear at all, js content shown
Content in <div> element may momentarily appear before being hidden, js
content shown
For this case, using <div> element is advantageous.
In summary
Use <noscript> element if rendering of the HTML content depends on third-party scripts or if the required script is inline. Else, use <div> element and make sure that the required script contains:
document.getElementById('noscript').style.display='none';
Although Tor Valamo has an elegant answer to this problem, there is an issue which may cause you to opt out of using this technique.
The problem is (usually) IE. It has the tendency to load and execute the JS a bit slower than other browsers causing it to sometimes flash the "Please Enable Your Javascript" div for a split second before it then loads the JS and hides the div.
It is annoying and to get around this you can implement the "classic". <noscript> redirect approach.
<head>
<noscript><meta http-equiv="refresh" content="0; URL=/NO_SCRIPT_URL/ROUTE_HERE"/></noscript>
</head>
This is the most solid technique that I've come across with regards to this little nasty.
One useful application for noscript that I've seen is for a progressively-enhanced async loading of heavy content (especially "below the fold"). Big images, iframes, etc. can be wrapped in noscript in the HTML source, and then the unwrapped elements can be appended to the page using JavaScript after the DOM is ready. This unblocks the page and can make for a much quicker initial loading experience, especially if your interface relies on JS/JQ interactions applied after the document is ready (2 seconds vs. 6 seconds for a portfolio page I consulted on).
These days it seems almost every browser runs Javascript, but you can never know who is going to be accessing your site. These days even screen readers and web crawlers use Javascript, and sometimes make AJAX requests if they have to.
That said, if you're going to fall back to no-Javascript, there is a much better way than a <noscript> tag. Simply do this in the HEAD of your document:
<script type="text/javascript">
document.getElementsByTagName('html')[0].className += ' Q_js'; // better than noscript
</script>
With this technique, you can easily refer to the Q_js class in your CSS to hide things. With the <noscript> tag, the best you can hope for is to include an additional CSS file to override previous CSS. This becomes important when some elements with static content are supposed to be hidden right away (not flicker) until Javascript can make them more dynamic.
In short, the technique I suggested addresses all your cons 1-5, and I believe it's strictly better than using <noscript>.
In the (hopefully near) future you will be able to use css #media scripting:
#media (scripting: none) {
/* styles for when JS is disabled */
}
I create a full height, full width, position:fixed div in all pages with some id .
<div id='noscript_div' style='position:fixed;z-index:20000000;height:100%;width:100%;line-height:100%;'>enable JS buddy</div>
$('#noscript_div').hide();
$(document).ready(function(event){
});
I am not an expert . This worked for me .
I am sorry but, this case will suit only if you want the user to have his javascript enabled always
the simple ideea is in this times your website may adapt to no javascript usage on slow devices using noscript tag like an entity for the entire content of your website**(your html should be prepared to no javascript and all controls must work also if javascript is off,users using basic html controls shoul be able to do everything they done before when javascript was active.So <noscript></noscript> can be the dynamic switch to the same content in other way with the same results=solving the problem wich is the reason the users open your url).**You can see is no matter javascript is or not present ,the website's functionality can be "the same" in any cases js enabled / disabled.On chinese slow devices eg:Samsung neo mini phone this method can run an website without any delays on low internet traffic..
try to run this auto double functionallity website if js is on/off cases:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE>noscript can change the Internet forever</TITLE>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
$(document).ready(function(){
$('noscript').replaceWith(function() {
return this.textContent || this.innerText;
});
$("p#javascripton").css("background-color", "yellow");
$("p").click(function(){
$(this).hide();
});
});
//-->
</SCRIPT>
<noscript>
<p>
Noscript's usage today can be logical for <p id="javascripton">eg pc/laptop/high quality tablets usage the complete website with all features:images high resolution,javascript<br><h1>OR without javascript so no high resolutions images inserted with a jquery automated script generated from some php+javascript scripts so have usage for 80% mobile application cause almost are from China ,so low quality products=low cpu,low ram :IN THIS CASE SOMEONE CAN THINK TO SWITCH HIS PHONE TO NO JAVASCRIPT USAGE SO IF ANY PROGRAMMER CAN ADAPT AN ENTIRELY APPLICATION TO THE METHOD I USED IN THIS EXAMPLE AUTOMATED HIS BROWSER IS ADAPT FOR ANY RANDOM ACTION ABOUT THE USER CHOISE(YOU UNDERSTAND "TO USE OR NOT JAVASCRIPT") SO HIS CHINESE PHONE CAN BE APROXIMATELLY APROACH LIKE QUALITY OF SPEED EXECUTION THE OTHERS PC/LAPTOPS/TABLETS QUALITY PRODUCTS.<BR><BR>This stupid example is the best example how no script tag can change the quality of services on this planet ,boost the speed of the internet connection and stops unnecessary use of A LOT OF INTERNET TRAFFIC on slow devices..a simple tag can change the entirely dynamic of programmer's views so entirely Planet's beneficts</h1><p> <br>
run this code in two instances :<br>with browser javascript enable <br>and without(browser's javascript disable or eg a firefox plugin noscript states on/off)
</p>
</noscript>
</BODY></HTML>
and to say more on this .. right noscript was invented to work like a trigger when js is disabled but you can work around this feature to change the course of internet functionality about how is now ,to change it's dynamics....
Like all things, use the right tool for the job.
If you are using Google Maps API, you have a static image via tag and that gets replaced with dynamic JS map. Google have recently started charging for everything thus with the above example it's going to cost you twice, once for static and once for dynamic. The static map is only relevant if JS is disabled. Therefore to save double paying it seems to me the best solution is to wrap the tag for the static map in a tag.

Categories