In HTML is there such a line of code that will do the same thing as PHP's require_once? I'm just curious because there are some lines of codes that I want to duplicate through multiples sheets without needing to require myself to type it each page.
I know I can do it via PHP, but I am looking for an HTML variant? Is there such a beast or am I barking up the wrong tree?
That depends on what you want to include. Including a PHP-File is not possible, if you want to include a CSS stylesheet, use:
<link rel="stylesheet" type="text/css" href="yourstylefile.css" />
and for a Javascript file
<script type="text/javascript" src="yourscriptfile.js"></script>
Of course you have to put that code between the header-tags.
No, there is no include mechanism in HTML. Unless you count SSI.
Edit: wait, "sheets"? You mean CSS?
Yeah, SSI is the closest you're going to get. However, there are many non-server-side ways to get around this. Several web development applications have html templating systems that replicate server-side includes on the development side. For example, dreamweaver allows you to insert repeatable regions into HTML templates. When you modify the "included" file, Dreamweaver will modify all HTML files that use that block. As this is not a true include, but rather an HTML-updating system, you do have to then re-upload these files if you use a remote server, but if you have to stick to plain HTML it can make projects much more manageable and is much better than using iframes.
Lastly, there is also the option of having Javascript build a repeating block of code. You can simply include a common javascript library on every page <script type="text/javascript" src="templater.js"></script> and have it build the element on the client's side (either with an innerHTML call or inserting elements into the DOM). This has the obvious downside that
It requires Javascript to work
It might mess with SEO
It may slow down page loads (from the client side anyhow)
Using a proper include in a server side language is of course the best approach, but in a pinch these are both potential alternatives.
Technically you can create an iframe on your page which will load and handle a separate page but it does not function like include or require once. And to this I know of no alternatives.
Related
It should be in View part, where the html is, or not? If this javascript code is used just for that one file, it doesn't make sense to put it in main file of javascript, does it? Thanks.
Inline JavaScript does not require an additional HTTP request,
and can incorporate with PHP logic,
but for repeat visitor will need to fetch the 15 lines of JavaScript all over again.
Using a JavaScript file incurred an additional HTTP request,
with the proper expiration header,
it won't repeatedly request the JavaScript file.
Of course, you can not incorporate PHP logic into it.
There is no clear winner, much depend on your situation.
I prefer inline JavaScript as the flexibility to incorporate PHP logic is irreplaceable.
And google does that too!
By minify inline CSS and JavaScript.
In a .js file, linked by a <script> in your HTML view.
Agree with prev answers. Cleaner to have it in a separate js file. Also to note that if possible, and there are very few cases where it's not, but I would recommend putting te references to te files at te bottom of the document and triggering functions, etc after the document is ready/loaded. you may want to look at some utilities that can also help you organize what files get referenced on what page.
If you want to access the javascript methods in more than one file. Then you should create a file with .js extension and place your methods or functions inside that file. Then open the files you actually want to access the javascript methods. between ... tags. Place like this
<script type="text/javascript" src="myscript.js">
http://www.pageresource.com/jscript/jxtern.htm
Simple and fast question:
I need the jquery library for a site, so I access it in my header.php file as such:
<head>
<!-- include jQuery library -->
<script type="text/javascript" src="../javascript/jquery.js"></script>
</head>
Now my question is should I also be putting some other php scripting in there to make sure it is only included when I need it for a given page? My gut tells me I am absolutely right to only load the jquery files when I need them, yet I swear I always see things like this loaded without thought to if they are actually needed for the given situation. So perhaps there is no harm in always having it there.
So should it be like this?? Pseudo code:
<head>
<?php
//set jquery variable to true or false in configure.php file based on situation
if($jquery){
//include the jquery script!!
}
else{
//jquery??? we don't need that here
}
?>
</head>
It's generally better to load only what you need for a page, but if you do include jQuery everywhere, make sure:
1) It's minified (to reduce overhead).
2) You serve from a CDN (e.g. Google's). The likelihood of the user having a cached version (and thus a faster page load) will be much higher. See:
http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/
It's not that big a deal.
Keep in mind that (most) people's browsers will cache files, for at least a certain duration of time. If say your homepage doesn't require jQuery, but the about page does, people with slower internet connections will be suffering a longer page load duration on your about page.
Even so, you should absolutely try to use minified versions of jQuery to reduce the amount of data you have to serve, and your users have to download. Even better is to use a CDN like Google's, as they're optimised for distribution to users, and also because with it in use widely, people are more likely to have it already cached on their system. HTML5 Boilerplate has a nice way to include jQuery from the Google CDN, and use the copy on your server as a fallback:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<script>window.jQuery || document.write('<script src="path/to/jquery-1.5.1.min.js">\x3C/script>')</script>
The issue of longer page loads can also be somewhat offset by having your jQuery include tag before the </body> tag, as scripts and stylesheets block page load until they're fully downloaded (for the majority of browsers). The only issue with doing that is that anything that depends on jQuery for site interaction of course won't respond immediately.
Given, if you absolutely want to conditionally include jQuery, that code snippet you provided should work fine.
I am assigned a task to revise a website and at present, I am working on index.html page. the previous coder has mixed a lot of JavaScript and CSS code in between and it is becoming difficult to read.
I want to know whether it is necessary to include <script> tags and CSS code in between? What about PHP code? Where each must reside?
Edited:
If multiple JavaScript and CSS files are to be referenced, how to include in a single <script> or <link> tag?
Keep your JavaScript inside a separate file, keep your CSS inside a separate file and have them both referenced from within your HTML. The order of these referenced files relative to the HTML does not matter. As for the PHP, I wouldn't worry too much about it being mixed in with the HTML (just keep your functions, classes and other scripts in separate files and include them with PHP in the header).
If is the same CSS on each page, having an external file that caches help to save bandwidth. If there are different rules intermixed with the HTML for different element types you may have some conflicts, but if you rewrite it, it will end up being a lot cleaner and easier to maintain later.
I like to keep a file structure like so:
index.php
/css
main.css
othercssfiles.css
/javascript
main.js
otherjsfiles.js
/template
header.php
footer.php
/scripts
functions.php
otherscripts.php
Then in my header file, I would place HTML code referencing the files in the CSS and JavaScript directories. And in the root directory my index.php file would include(); the header at the top and the footer at the bottom.
otherjsfiles.js and othercssfiles.css can be used in cases where a single page may have a specific requirement, requiring a lot of CSS and JavaScript that most other pages don't need. It means other pages do not need to fetch unnecessary data and it keeps page specific code separate from the entire site's code.
I have found this an easy way to keep track of various aspects of the code that makes up an HTML page, but naturally, you will find ways to organize it that makes sense to you.
Edited:
If multiple JavaScript and CSS files
are to be referenced, how to include
in a single or tag?
It would be better to combine them into a single file to conserve HTTP requests (which take time). Then you would just include those CSS and JavaScript files like normal.
<script type="text/javascript" src="/javascript/main.js"></script>
<link rel="stylesheet" href="/css/main.css">
Additionally, it seems like you could use the services of a CSS beautifier for readability, a JavaScript beautifier for readability and a JavaScript minifier for when you are done reading it (keep the readable version) and want to save bandwidth. These tools are especially helpful when you are working on maintaining a website you did not create.
Rarely is there a valid reason for CSS be mixed into the HTML - a separate file is generally best.
With JavaScript: there may or may not be a good reason for it being mixed into the code. E.g. if a piece of script is dependant on running after one element of HTML is loaded and before another. This isn't a particularly good coding practice, but if you're updating an existing site you may be stuck with it.
In the end the only way to really tell is to pull it out and make sure the page still works.
As Sam said, keep JavaScript and CSS external, and reference items in the JavaScript by id rather than onclick= etc. Follow Yahoo, and put the CSS in the <head> and the JavaScript before the closing <body> tag.
For multiple JavaScript or CSS, use multiple <script> or <link> tags.
As for PHP, it's good practice to keep as much of the functionality in a separate include file, and just call functions etc. in the main HTML. This will aid maintainability greatly. Aim for simple loops, if/elses, and function calls, and nothing else.
If multiple javascript and CSS files
are to be referenced, how to include
in a single or tag?
You either reference each file using multiple tags or use a minifier like YUI compressor to create a single CSS and JS file from the originals.
The order of CSS styles is relevant, but only relative to other CSS styles. So, start by moving all CSS styling together (in the head section) in the same order as originally. That will make it somewhat less messy while defenitely not changing how the page works.
Then you can start looking at whether you can rearrange scripts and PHP code. What they output to the page directly is relevant, otherwise they can easily be rearranged.
PHP coding allows you to have HTML/CSS interspersed with PHP code by using server tags like <? -php code here -?>.
This is normal - it is very flexible and easy-to-get-started.
Your JavaScript should ideally be placed into a separate JS file and using the <script> HTML tag to reference it. See the docs.
Your CSS should ideally be placed into a separate CSS file and use a <style> HTML tag to reference it. Again, see the docs.
While writing code in a file that would comprise of PHP, HTML, CSS & JavaScript, in what order each must appear? What are the best practices for separating the presentation and the logic?
Sometimes external .js and other files are using in the link tag. Where these link tags must appear?
This doesn't answer the question directly but the article that Rasmus Lerdorf (creator of PHP) wrote has some nice examples to follow.
Clean and simple design. HTML should look like HTML. Keep the PHP code in the views extremely simple: function calls, simple loops and variable substitutions should be all you need
http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html
most if not all javascript should be external files linked from either the header (between the tags) or all the way at the bottom near the closing tag depending on how youre enhancing the page.
css should never be inline in my opinion. start with external css files linked from the header, and if you must go to the file level. ie.
<head>
<style type="text/css">
/* CSS CODE HERE */
</style>
</head>
as far as php best practices, dont do a database call in your html templates. keep the templates simple php. if's for's to echo out your database results.
Your tags should (must?) go in the head of your page.
There are a handful of exceptions, but most of the time your CSS will be in an external .css file that you'll link like the .js files you mention. The order you need to load your external scripts may depend on their content. For example, if you're using jQuery plugins, you'll need to load the jQuery library before the plugin file.
PHP and HTML will often be intertwined within a document. There are discussions on SO and elsewhere over how HTML should be displayed within PHP (e.g.
?> <!--html goes here--> <?php
or
echo '<p>This is my html</p>';
..but I've never seen a definitive answer to either method. Use whichever makes you file legible.
All of this must be in different files except of very small portions (for example js in html).
The best place for link tag is in head section of html.
I have a website which consists of a bunch of static HTML pages. Obviously there's a lot of duplication among these (header, menu, etc). The hosting company I plan to use supports PHP, which I know nothing about. Presumably PHP provides some sort of #include mechanism, but what changes to I need to make to my HTML pages to use it?
For example, suppose I have a page like this
index.html
<html>
<head></head>
<body>
<h1>My Common Header</h1>
</body>
</html>
Obviously I need to move the common part into it's own file:
header.html
<h1>My Common Header</h1>
Given the example above (and assuming all files are in the same directory):
What do I add within the body tag to get header.html included?
Do I need to rename index.html or add some special tags to indicate that it's a .php file?
Do I need to make any changes to header.html?
Update: I want to emphasise that my objective here is simply to find the lowest-friction means of reducing duplication among static HTML files. I'm a bit reluctant to go down the server side includes route because I don't yet know what type of server (IIS/Apache) I'll be hosting the files on, and whether includes will be turned on or off. I was drawn towards PHP only because it is about the only thing I can presume will be available that will be able to do the job. Thanks for the responses.
Thanks,
Donal
You are looking for include (or one of its derivative such as include_once, require, require_once):
header.php
<h1>My Common Header</h1>
index.php
<html>
<head></head>
<body>
<?php include('header.php'); ?>
</body>
</html>
And so on, for your footer for example.
You don't need to use PHP to get this functionality, and it's generally a bad idea to do so due to potential security concerns. Essentially, you're swatting a gnat with a nuclear bomb. If you're not using a dynamic language, then you're looking for server side includes.
In IIS, for instance:
<!--#include virtual="file.inc"-->
Be aware that you often have to configure the server to utilize them, as this feature is often turned off by default. Both IIS and Apache support server side includes, but they use different configurations.
You can find more information here:
Server Side Includes
EDIT: I don't mean that it's a bad idea to use PHP, just using PHP solely for including other files. It creates a larger attack surface by bringing PHP into the mix when it's not needed, thus the potential for security issues when the functionality of PHP is not required.
EDIT2: I think it's a bad idea to assume you won't be a target because of your size, and thus you can ignore security. Most sites are compromised by automated worms and turned into malware hosts, spam zombies, or pirated software/media servers. Apart from the fact that you might end up being involved with infecting others, your site can become blacklisted and it can cost you real money in bandwidth overage charges. We're talking hundreds or thousands of dollars.
Just because you're a small site doesn't make you any less of a target. Just being on the internet makes you a target.
Forget doing it on the server altogether.
If all you really want to do is maintain some static pages -- and don't anticipate ever having to really use PHP -- I'd just do it with Dreamweaver, which will allow you create and manage templates and variable content on your end.
No includes needed. No templating engine needed. (These would be overkill for what you are trying to accomplish.)
You should first change the file extensions of index and header to be .php, then you can do:
<html>
<head></head>
<body>
<? include 'header.php'; ?>
</body>
</html>
And your header.php file just has
<h1>My Common Header</h1>
While you can just use the "include", "require", or "require_once" directives to include things in one page, you might have better luck with a template engine like Smarty
While using an include file for the header is a solution I went a different route when I faced the problem several years back: I wanted all pages to use the same layout (which I assume is rather common ;-). Thus, as I only wanted to change the content of the page I made the page content the file that gets included and have a master template file that includes header and footer. For setting the page to be included I resorted to creating quite small php scripts that only set a variable that holds the page to get included. In some cases the page can also get named by a GET parameter. Of course this requires proper validation of that parameter. In the long run I don't need to worry about the HTML itself anymore -- all I do is write small snippets (which should be complete for themselves of course) that get included.
A possibly even better solution would be to use an existing template framework. Due to the contraints I had back then I wasn't able to do so, but I would do it when facing the same issue again.
Back in the day, I used SSIs (the "<!--#include virtual="file.inc"-->" method described above by Mystere Man) quite a bit for static HTML pages and I would definitely recommend using that.
However if you want to eliminate any uncertainty about whether support for that will be enabled on the server, you could develop your separate files locally and merge them into the resulting files before uploading to your server. Dreamweaver, for example, supports doing this in a seamless fashion.
Or you could do it yourself with a rather simple script in your language of choice by doing simple string replacement on markers in the files, replacing {{{include-header}}} with the contents of a "header.html" file and so on.
Edit
Oops! Somehow I didn't see Clayton's post with the same note about Dreamweaver.
OK this is a semi-programming related question only.
PHP does have include(), which is really easy to use, but it doesn't contribute to future maintainability. I wouldn't recommend it, especially for big sites.
I'm a pro-frameworks. I've used CodeIgniter, CakePHP and even Smarty template engine. If you are serious about PHP, do consider CakePHP. There's this "layouts" concept where you frame your header, footer, css, javascript outside of the main content; e.g. for the "about us" page, your content would be something like:
This is an about us page that tells you a whole bunch of stuff about us...
CakePHP takes this this content, and wraps your layout around it:
header
css
javascript
This is an about us page that tells you a whole bunch of stuff about us...
footer