Grow your CSS skills. Land your dream job.

How to load CSS using javescript

  • # January 22, 2013 at 3:06 am

    Hi guys,

    i want to ask, is it possible to load css using javascript ???

    because i have 2 css files, 1 for the desktop and the other one for the mobile browser/touch device

    # January 22, 2013 at 3:23 am

    It is indeed possible.

    var s = document.createElement(‘link’);
    s.setAttribute(‘href’, ‘style.css’);
    document.head.appendChild(s);

    But sometimes using JavaScript isn’t the best idea. Have you thought about using media queries instead?

    # January 22, 2013 at 3:30 am

    Seconded. Use media queries instead of JavaScript.

    # January 22, 2013 at 3:40 am

    Here’s an introduction to media queries that Chris wrote: http://css-tricks.com/css-media-queries/

    # January 22, 2013 at 4:01 am

    @rosspenman and @HugoGiraudel, thanks a lot guys.

    # January 22, 2013 at 6:44 am

    I disagree using css is many ways better. Here are 7 clean ways to do it. FYI the last one is the best http://www.visibilityinherit.com/code/add-css-with-javascript.php

    # January 22, 2013 at 6:54 am

    The issue here is that there are two CSS files targeted specifically for different environments, desktop & mobile.

    Media queries could reduce this to a single CSS file but if the separate files are required then there is no reason that the ‘media query’ couldn’t be in the head of the page to load the css file appropriate to the screen/device width.

    Something like:

    # January 22, 2013 at 9:14 am

    @Paulie_D default is all correct?

    # January 22, 2013 at 9:16 am

    so you could just say media=”() and ()

    # January 22, 2013 at 9:40 am

    media = all will media types of which there are many.

    If you want to limit it to screen devices (say you don;t want it for printing purposes) then you could change it to media=”screen”.

    # January 22, 2013 at 9:16 pm

    @Eric, why did you say “I disagree using css is many ways better”, can you explain it a little bit ?

    i’m still new so there’s many thing i must learn

    @Paulie_D thanks for the answer

    # January 22, 2013 at 11:46 pm

    Paulie no I’m saying I believe media all is default. So if you exclude media all it will still target all.

    Kiddo. My link explains why it’s good. But I guess it comes down to what your using it for. From the sounds of it I guess media queries would be better in your case. Usually you use javascript to feed css when you don’t want the css applied when JS is off.

Viewing 12 posts - 1 through 12 (of 12 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".