2
\$\begingroup\$

I currently have a WP site and in the header, I've put this in:

...
<body <?php body_class('no-js');?>>
    <script>document.body.className = document.body.className.replace( 'no-js' , 'js' );</script>
...

It works flawlessly and I've got no complaints, as it accomplishes the following:

  • Does not rely on jQuery to load, which is placed at the bottom of the code after the body element along with other js files.
  • Runs before the visible elements are loaded and doesn't change the look of the site after the site has loaded, meaning the user sees exactly what is supposed to be seen.
  • Code is placed immediately after the body element is opened so it can find the body after the browser reads that it exists, meaning it's quick, small, and easy to spot.

I'm wondering if there's a more efficient way of doing this.

Solution doesn't have to be js; it can be anything, as long as it's the right way. Obviously I'm using the classes to distinguish when js is working or not for the corresponding CSS styling to apply.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ What do you intend to do with the no-js class? \$\endgroup\$ – 200_success Apr 22 '17 at 22:24
  • \$\begingroup\$ I intend on using it to reveal elements that would otherwise be hidden and reveled through the use of js. That's an example. My css needs to know when js is on or off so it would style accordingly. \$\endgroup\$ – yaharga Apr 22 '17 at 22:30
3
\$\begingroup\$

It's a decent and pretty bullet-proof solution. Modern browsers also support the classList API, so you can do:

document.body.classList.remove('no-js');

It's a slightly safer solution, as the original could technically replace parts of a word (like abcno-jsfoo). Not really a concern here, but still.

To avoid that, and still use the original solution, you could use a regular expression to match word boundaries too:

document.body.className = document.body.className.replace(/\bno-js\b/, '');
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.