Can I create a common include file in HTML? [duplicate] - javascript

Is there a decent way with static HTML/XHTML to create common header/footer files to be displayed on each page of a site? I know you can obviously do this with PHP or server side directives, but is there any way of doing this with absolutely no dependencies on the server stitching everything together for you?
Edit: All very good answers and was what I expected. HTML is static, period. No real way to change that without something running server side or client side. I've found that Server Side Includes seem to be my best option as they are very simple and don't require scripting.

There are three ways to do what you want
Server Script
This includes something like php, asp, jsp.... But you said no to that
Server Side Includes
Your server is serving up the pages so why not take advantage of the built in server side includes? Each server has its own way to do this, take advantage of it.
Client Side Include
This solutions has you calling back to the server after page has already been loaded on the client.

JQuery load() function can use for including common header and footer. Code should be like
<script>
$("#header").load("header.html");
$("#footer").load("footer.html");
</script>
You can find demo here

Since HTML does not have an "include" directive, I can think only of three workarounds
Frames
Javascript
CSS
A little comment on each of the methods.
Frames can be either standard frames or iFrames. Either way, you will have to specify a fixed height for them, so this might not be the solution you are looking for.
Javascript is a pretty broad subject and there probably exist many ways how one might use it to achieve the desired effect. Off the top of my head however I can think of two ways:
Full-blown AJAX request, which requests the header/footer and then places them in the right place of the page;
<script type="text/javascript" src="header.js"> which has something like this in it: document.write('My header goes here');
Doing it via CSS would be really an abuse. CSS has the content property which allows you to insert some HTML content, although it's not really intended to be used like this. Also I'm not sure about browser support for this construct.

The simplest way to do that is using plain HTML.
You can use one of these ways:
<embed type="text/html" src="header.html">
or:
<object name="foo" type="text/html" data="header.html"></object>

You can do it with javascript, and I don't think it needs to be that fancy.
If you have a header.js file and a footer.js.
Then the contents of header.js could be something like
document.write("<div class='header'>header content</div> etc...")
Remember to escape any nested quote characters in the string you are writing.
You could then call that from your static templates with
<script type="text/javascript" src="header.js"></script>
and similarly for the footer.js.
Note: I am not recommending this solution - it's a hack and has a number of drawbacks (poor for SEO and usability just for starters) - but it does meet the requirements of the questioner.

you can do this easily using jquery. no need of php for such a simple task.
just include this once in your webpage.
$(function(){
$("[data-load]").each(function(){
$(this).load($(this).data("load"), function(){
});
});
})
now use data-load on any element to call its contents from external html file
you just have to add line to your html code where you want the content to be placed.
example
<nav data-load="sidepanel.html"></nav>
<nav data-load="footer.html"></nav>

The best solution is using a static site generator which has templating/includes support. I use Hammer for Mac, it is great. There's also Guard, a ruby gem that monitors file changes, compile sass, concatenate any files and probably does includes.

The most practical way is to use Server Side Include. It's very easy to implement and saves tons of work when you have more than a couple pages.

HTML frames, but it is not an ideal solution. You would essentially be accessing 3 separate HTML pages at once.
Your other option is to use AJAX I think.

You could use a task runner such as gulp or grunt.
There is an NPM gulp package that does file including on the fly and compiles the result into an output HTML file. You can even pass values through to your partials.
https://www.npmjs.com/package/gulp-file-include
<!DOCTYPE html>
<html>
<body>
##include('./header.html')
##include('./main.html')
</body>
</html>
an example of a gulp task:
var fileinclude = require('gulp-file-include'),
gulp = require('gulp');
gulp.task('html', function() {
return gulp.src(['./src/html/views/*.html'])
.pipe(fileInclude({
prefix: '##',
basepath: 'src/html'
}))
.pipe(gulp.dest('./build'));
});

You can try loading them via the client-side, like this:
<!DOCTYPE html>
<html>
<head>
<!-- ... -->
</head>
<body>
<div id="headerID"> <!-- your header --> </div>
<div id="pageID"> <!-- your header --> </div>
<div id="footerID"> <!-- your header --> </div>
<script>
$("#headerID").load("header.html");
$("#pageID").load("page.html");
$("#footerID").load("footer.html");
</script>
</body>
</html>
NOTE: the content will load from top to bottom and replace the content of the container you load it into.

No. Static HTML files don't change. You could potentially do this with some fancy Javascript AJAXy solution but that would be bad.

Short of using a local templating system like many hundreds now exist in every scripting language or even using your homebrewed one with sed or m4 and sending the result over to your server, no, you'd need at least SSI.

The only way to include another file with just static HTML is an iframe. I wouldn't consider it a very good solution for headers and footers. If your server doesn't support PHP or SSI for some bizarre reason, you could use PHP and preprocess it locally before upload. I would consider that a better solution than iframes.

Related

Modern JS method of PHP 'include' function

With the ever-growing library of JS frameworks (since I last build a website ~ 2014) is there a simple JS replacement/alternative for PHP's 'include' function. Or is PHP include still a relevant method of including chunks of code?
I'm building a website and want to achieve some basics like 'including' footers, headers, menu's etc. but would rather not make all my pages .php - it feels a bit clunky and unnecessary.
I found a related post here referencing Jekyll but it was a bit more specific to GitHub. Any pointers in the right direction appreciated!
Since my first answer wasn't covering the interested question I decided to fully edit and replace the answer. Here we go..
Solutions
1 - JQuery load() function
<!-- LOAD JQUERY -->
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<!-- "INCLUDE" external files with code -->
<script>
$("#header").load("header.html");
$("#footer").load("footer.html");
</script>
2 - NPM gulp package which lets you includes file and pass some parameters/values
https://www.npmjs.com/package/gulp-file-include
<!DOCTYPE html>
<html>
<body>
##include('./header.html')
##include('./main.html')
</body>
</html>
an example of a gulp task:
var fileinclude = require('gulp-file-include'),
gulp = require('gulp');
gulp.task('html', function() {
return gulp.src(['./src/html/views/*.html'])
.pipe(fileInclude({
prefix: '##',
basepath: 'src/html'
}))
.pipe(gulp.dest('./build'));
});
3 - pure javascript via document.write function and including script with it via src
<script type="text/javascript" src="header.js"></script>
4 - pure ajax request that requests additional data and places it where it should be placed on the page
5 - SSI (Server Side Include), as I mentioned it in comment
6 - iframes (not the best way, though)
7 - asp/jsp server script include (as alternative to php server script include)
More info here:
Common Header / Footer with static HTML
Make header and footer files to be included in multiple html pages
Hopefully you can find the best way that will suit your needs from one of this.

Custom Javascript in EJS templates using Sails.js

I'm getting wet with Sail.js, which I love so far, but I'm stuck on a simple question: If I have a javascript function that I want to run just on a particular view, where do I invoke it?
A very simple example would be this:
//contact.ejs
<div id="contact"></div>
<script>
renderContact();
</script>
Let's assume renderContact is defined in my master JS file for the site, and does what it sounds like: Creates a contact list in <div id='contact'></div>.
Of course, that master JS file, as well as all vendor JS, doesn't get loaded until AFTER this script tag since it's injected into layout.ejs, so that function will be undefined. I could always natively wait for the page to load like so:
document.addEventListener("DOMContentLoaded", function(event) {
renderContact();
});
But that seems like a horrible solution.
I realize that Sails integrates powerfully with Angular, React, and so forth, but I first want to understand the basic way that one invokes JS to a single page before I get fancy. There must be a better way to run certain functions only on certain pages once the DOM has loaded?
So for renderContact to work it should look like this:
<html>
<head></head>
<body>
HTML
<script src="master.js"></script>
<script>
(function() {
renderContact();
})();
</script>
</body>
</html>
The downside of ejs is that AFAIK it does not support blocks. It's kind of bare metal. So you have to put all your scripts in the main layout file and the scripts will be around on pages where they are not needed. But you can configure other template engines in sails, like jade. Jade supports blocks which you can override or extend. Here is an example of jade blocks: https://stackoverflow.com/a/22748166/401025

Calling "HTML components" from within JS files

I've been seeking to use Javascript to load content just the way PHP does with require, require_once and include, so I came to this:
In the HTML source:
<script src="footer.js"></script>
The footer.js file:
document.write('<footer id="footer" class="fluid"><div id="callaction"><p>A sua saúde está em dia? Confira aqui</p></div><p>©2015, CUIDAR SAÚDE. Todos os direitos reservados</p><p>André Lemos - Master Design</p></footer>');
It works, but since I'm not a JS expert, I ask: Is this a bad thing to do? Do I have to concern about performance problems? Better ideas?
Yes, it is a good idea to implement. But, take care. Since you are importing footer the script tag is supposed be written at the end of whole html content.
Linking the JS script which outputs something to the document isn't very good idea. The concept has several problems:
the browser must open a new client-server connection and/or make a HTTP request,
the reason 1 slows down the pageload (primarily if the script is linked before the main page content),
some search crawlers can't recognise (and thus index) the content "included" this way.
But you also have to consider the situation in which you wanna use this "content including" before you use or let it. If you just use it for common footer, the concept might be satisfiable.
If you want/need to use some server-side solution because of the problems described above, but you don't want to use PHP and its include statement, you could try Server-Side Includes module for Apache.

Include a JavaScript file as it was written in a script tag

I have some html, that had a bunch of JS code inside a script tag. So I moved it to a separate .js file.
JS code also loaded some variables from CGI, using strings in a form of <%ejGet(var)%>. But after separating the code from HTML file, the strings don't get replaced with data from the server.
Is there a way to include a JS file as if it was written inside a script tag or is there another way to do this?
<script language="javascript">
<!-- hide
var syncNvram = '<%ejGetWl(wlSyncNvram)%>';
...about 1000 lines more...
</script>
So after moving this code to a separate file, the variables don't load.
The problem is that your <% ejGetWl(wlSyncNvram) %> is being executed on the server by some templating or processing engine before it gets sent to the browser, so the browser is actually seeing the output, e.g.
var syncNvram = 'abcdefg'; // or whatever the output is
The question you are really asking is, can my server side templating/processing engine process a javascript file as opposed to an html file.
The answer is, it depends on the template/processing engine, but in general, this is a bad idea. JS files should remain static assets for lots of good reasons (breaking code, distributing via CDNs, etc.)
The better thing to do is separate them out:
<script>var syncNvram = '<%ejGetWl(wlSyncNvram)%>';</script>
<script src="myfile.js"></script>
Declare it separately.
Even better might be using ajax to get it, but that is a whole different architecture which may not suit here.
To do that you need to generate the script from the CGI program.
<script src="/cgi-bin/example.js.cgi"></script>
Of course, that will be a different CGI program so getting the variables in the right state may be problematic.
Usually you would solve the problem using a different approach: include the data in the document (either in the script element or in an element such as a <meta> element, a hidden input or a data-* attribute on something relevant and then have a static script read the data from the DOM.

Multiple sources for a javascript file

I am working on a project where I need to include somewhat around 10-15 .js files in the HTML head section directly like
<script type="text/javascript" src="http://localhost:9020/website1/wa/min/soundmanager2.js,vars.js,utils/md5.js,utils/utils.js></script>
what is the way I can give refrences correctly
the files I need to refre are in the same hierarchy like
1.....2,3
2.........4,5
3........6,7
I need to refer 1,4,7 please help.
somewhere I read this method what's it?
<script type="text/javascript" src="http://localhost:9020/wordplus/root/child/?b=scripts&f=soundmanager2.js,vars.js,utils/md5.js,utils/utils.js></script>
The example you posted looks exactly like the query string interface for the minify PHP library: http://github.com/mrclay/minify
Using it you use it in the fashion <script src="min/?b=path&f=script1.js,script2.js,ui/script3.js"></script>.
Where path is the path from your web root that you want it to look for scripts under.
I've used it before and I've found it quite effective. It concatenates, minifies, caches, and serves JS and CSS.
I'm sure there are other libraries to achieve the same effect, alternatively you can create a build script to concatenate and minify all your scripts and then deploy a single JS file to your site, in a single script tag.
It is not possible to load multiple javascript files in a single <script> element.
You have to have to have an individual <script> element for each script you are referencing..
<script type="text/javascript"
src="http://localhost:9020/wordplus/root/child/?b=scripts&f=soundmanager2.js"></script>
<script type="text/javascript"
src="http://localhost:9020/wordplus/root/child/?b=scripts&f=vars.js"></script>
I think you'll get what you need from dynamically loading external javascript files:
http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
The second line you posted requests scripts from the server dynamically. the b parameter of the request tells it you want scripts and the f parameter tells the server which files you want. Then it concatenates these into one file and sends that back to the user agent. You need server-side scripting to handle this; it is not something built into the URL specification.
http://localhost:9020/wordplus/root/child/
b=scripts
f=soundmanager2.js,vars.js,utils/md5.js,utils/utils.js
The simplest solution is just have one script tag per file as it will let you take advantage of caching:
<script src="http://localhost:9020/wordplus/root/child/soundmanager2.js"></script>
<script src="http://localhost:9020/wordplus/root/child/vars.js"></script>
<script src="http://localhost:9020/wordplus/root/child/utils/md5.js"></script>
<script src="http://localhost:9020/wordplus/root/child/utils/utils.js"></script>
Another solution is to use some JavaScript builder to join all your files, generating just one. The pros of this approach is that your result file will be "compressed" (minified). Some builders:
Google Closure Compiler (I like and use this since 2009).
YUI Compressor

Categories

Resources