views:

117

answers:

2

i am confused by the concept of on-demand loading

I saw this blog post and was wondering if I could do the same with php using the ff. approach:

  1. check current url
  2. serve css or js based on current url

which may be done like this in Kohana

if (uri::segment(1) == 'search') // check current url
echo html::stylesheet('search.css'); // serve stylesheet
echo html::script('search.js'); // serve script
endif;

or am I getting the idea wrong?

a side question would be is ti alright to have a css file for each individual page aside from the site-wide forms.css and layout.css

+2  A: 

Here is an example for HTML and PHP using REQUEST_URI. the variable will hold the page you're at, you might want to do some parsing of it to get the exact page with out slashes etc, it's usually a relative path to the document from the root.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
<?php

switch($_SERVER['REQUEST_URI']) {
    case "/home.php":
     echo '<link type="text/css" href="home.css" rel="stylesheet" />';
     echo '<script type="text/javascript" src="js/home.js"></script>';
    break;

    case "/about.php":
     echo '<link type="text/css" href="about.css" rel="stylesheet" />';
     echo '<script type="text/javascript" src="js/about.js"></script>';
    break;

    case "/contact.php":
     echo '<link type="text/css" href="contact.css" rel="stylesheet" />';
     echo '<script type="text/javascript" src="js/contact.js"></script>';
    break;

    default :
     echo '<link type="text/css" href="default.css" rel="stylesheet" />';
     echo '<script type="text/javascript" src="js/default.js"></script>';
    break;
}
?>
</head>

<body>
My Page
</body>
</html>
Shadi Almosri
+1  A: 

you can use your approach. css files are better served in the head and so you can put your conditions in the site wide template.

for javascript, which should be served at the bottom of your html, you can simply put your tags directly in your application/view/your_action.php without using any url based condition.

about

would be is ti alright to have a css file for each individual page aside from the site-wide forms.css and layout.css

well, you can do it but keep in mind that this will generate an extra request (for the css files) for every new page visited by the user. if performance is critical you'd better serve a unique compressed css.

gpilotino