views:

86

answers:

4

i am making a "static" php website in this style

<?php include "header.php" ?>
<?php include "left.php" ?>
<?php include "photos.php" ?>

In "photos.php" i have 3 heavy javascript files from the lightbox and i thought it could be a good to include the javascript files only in this "photos.php" and not at the "header.php". But javascript supposed to be only in the head html tags. Do you have any better approach or mine is just fine?

thanks very much

A: 

If you're going down this route, you could try setting a variable before you include header.php which stores whether or not those JavaScript files are needed. It might not be necessary to sweat it too much though, if users tend to stick around on your website they'll fetch those files once and then not again, since hopefully your server will return a 304 Not-Modified response, and they'll be served from your browser's cache.

Dominic Rodger
+5  A: 

It's best to have all javascript in the head whenever you can. And you can without much difficulty. As Dominic Rodger said, it's probably not a big deal to include the js files on every page because they should be cached.

I tend to create page template class files with lots of variables for this sort of thing. A simpler thing to do that's more inline with what you're already doing is to set a variable before you include the header file, then access that variable in the header file and add the js if appropriate.

<?php 
    $includePhotoJavascript = true;
    include "header.php";
?>

In the header file:

 if(isset($includePhotoJavascript) and $includePhotoJavascript == true)
 {
    // add the javascript
 }
Scott Saunders
+2  A: 

JavaScript does not only have to be in the head HTML tag. It is actually advisable to put it at the end of the HTML file, because they halt the rest of the HTML file from loading.

What you could do in the header.php file, is something like this:

<html>
<head>
<title><?php print $title; ?></title>
<?php
foreach($javascript as $src){
?>
  <script type="text/javascript" src="<?php print $src; ?>"></script>
<?php
}
?>
</head>

Then the file you posted would look like this:

<?php
$title = "Photo album";
$javascript = array("jsfile1.js", "file2.js");
include "header.php" 
include "left.php" 
include "photos.php"

?>

Marius
I do this, except that I don't have the extra wrapper file including `photos.php`, I would just put the title/javascript variables and includes in photos.php itself, and make that the page that's loaded.
DisgruntledGoat
A: 

thanks very much for your ideas. i am planning of making the home page(index.php) as light as posible. So i will load javascript(lightbox.js) only in photos.php and try to do a LAZY LOADING to this lightbox.js so when "first time" visitor go to photos.php javascript file will be in cache. and all these in background. I think is the same Facebook does. Look here Optimizing Facebook

thodoris