Alternative solution to ondomready JavaScript support enabled
There are many JavaScript frameworks out there that allow you to work with the DOM before the page has completely loaded. Often you'll see the html or body tag manipulated in such a way as to determine if the user's agent has JavaScript support or not.
For example, the html tag will have a class of 'no-js' and when the DOM is ready, that class name is updated to be 'js' instead, thus allowing the front end developer to style the page in two ways - one with JavaScript support and the other in a way that will display the data properly when JavaScript is not supported.
This works fine, however there is always a bit of lag and you'll often see the screen jump when the updated class naming function is run (from 'no-js' to 'js') as a result of the differently styling applied to a JS-supported version of the site.
This has always annoyed me, and it can really look ugly if there is a lot of JavaScript-based interactivity on the page.
Long story short, my intent was to find a solution that would do this quicker than the ondomready
event. The solution I came up with was to run the following statement immediately after the opening body tag:
<script type="text/javascript"&开发者_运维知识库gt;//<![CDATA[
var elBody = document.getElementsByTagName('body')[0];
elBody.className = elBody.className.replace(new RegExp('no-js\\b'), 'js');//]]></script>
This appears to work great. No more screen jumping. Is this an ok approach to take? Any cons that I am unaware of?
I also run a script as soon as possible after the opening <body>
tag - it seems by far the best place for it. I only have one suggestion. This little script may run faster if you avoid the need for the regular expression. Perhaps simplify to something like this:
<body>
<script type="text/javascript">document.getElementsByTagName('body')[0].className='js';</script>
Then you can style the page for the non-JavaScript situation by default, and enhance using the js
class. For example:
/* Base styles for signin form, displayed inline on page */
#signin-form{
background: #fff;
color: #333;
/* ...other pretty form styles... */
}
/* JS enhanced floating signin form */
.js #signin-form{
display: none;/* removes form from DOM and shown by JavaScript */
position: absolute;
top: 0;
right: 1em;
}
There is also a CSS rendering advantage here, since the selector #signin-form
will run faster than .no-js #signin-form
.
Hope this helps!
精彩评论