Search code examples
phpjavascriptif-statementhead

Calling a .php file within a javascript if statement


Is there any way to remove the <head>, place it in a .php file and then use a javascript if statement in its place to call a certain head depending on screen resolution?

Now I know how to do the obvious if statement, and I've read about the complications of calling php within javascript due to client side vs server side, but, in the source code I can see the script appears, but doesn't work.

Any ideas?


Solution

  • From your comment, where you say that what you want to change in the head is "mainly stylesheets", I take it that you want to apply different stylesheets depending on the screen resolution and/or some other conditions. That you can do, but not the way you describe. Try something like the following instead:

    <html>
    <head>
    <script>
    if (whateveryourconditionis) {
       document.write('<link rel="stylesheet" href="sheet1.css" type="text/css">');
    } else (someothercondition) {
       document.write('<link rel="stylesheet" href="sheet2.css" type="text/css">');
       document.write('<link rel="stylesheet" href="sheet3.css" type="text/css">');
    } else {
       document.write('<link rel="stylesheet" href="default.css" type="text/css">');
    }
    </script>
    </head>
    <body>
    </body>
    </html>
    

    I wouldn't normally recommend document.write(), but for this sort of purpose while the page is still loading it's perfectly fine and simpler than the alternatives. If you prefer you can use document.createElement(); and then set the appropriate attributes and append it to the <head>, but I wouldn't bother with that unless you want to change the stylesheets after the page has loaded.

    You can also use a conditional loader library like YepNope.js (don't worry about its emphasis on loading JS files, it'll do CSS as well).