Stylesheets for content? - javascript

Forgive my ignorance since this seems like its something I should know by now.
I know I could make a stylesheet that will allow me to make changes in my CSS throughout several pages that use the CSS. I also know that you can make an external javascript file that could contain functions you want to reuse. But lets say I had pure HTML content (lets pretend a bunch of buttons or links) that I wanted replicated on several pages. Is there anything similar to a stylesheet in that regard? This would allow you to update the buttons/links all at once.

Try server-side includes.
The most frequent use of SSI is to include the contents of one or more files into a web page on a web server. For example, a web page containing a daily quote could include the quote by placing the following code into the file of the web page:
You could also use PHP, if your host allows it. Just change the name of the page from .html to .php and reference the header:
<?php include "header.php" ?>
Both of these require you to change the file's extension, so you might also want to use mod_rewrite to let users still access it via the .html name. Again, if your host supports it.

The question isn't that stupid, as there in fact is nothing native in HTML to do this.
If supported by your server, Server Side Includes are your best option. If you have PHP, you can also do a <?php include "footer.html"; ?>
All other server side languages have a similar construct.

Depends... I know Dreamweaver has some rather advanced support for templates. You can delve into the manual of your WYSIWYG HTML editor and get acquainted to how it can help you with repeatable content items. Otherwise, as Simon hinted, you should consider learning some server side technology (scripting language such as PHP is an easy choice), write your repeatable HTML and let the scripts output that whenever and wherever you need. Good luck!

It seems you're not using some server side technology like ASP.NET which has user controls on which you could place those.
An alternative would be to use Server Side Includes like:
<!--#include virtual="header.html"-->
Grz, Kris.

You can try using the CSS content property, but the content is inserted after/before the target. http://www.w3schools.com/Css/pr_gen_content.asp
EDIT
You can also try storing your content in XML documents and using JavaScript to load the XML sheets. Each sheet can store your button content, input content, etc. All you have to do is parse the XML and render the content as HTML elements.

While SSI seems like the best idea I believe, if memory serves me well, that if you're using IIS you're going to have to adjust some settings on the server to work get SSI with the html file extention.
While SimpleCoder's idea doesn't seem like the best idea it is an interesting one. Building on that idea maybe json data instead of xml would be best. I'd play around with this just for the fun of it.

If neither SSI or PHP is available, you could do it with javascript only:
Load the page into a hidden IFRAME, then grab it (with innerHTML)
- and move it to where you need it..

Unless you don't care about SEO, I would advise against using javascript for this purpose.
It's possible, but such a technique could prevent search engines from properly indexing your site.

Related

Include html files in an html file on a local file system?

I have a help system that is completely offline, no server, using file://.
I have one main page, with hundreds of line of html that represent many sections of the help system. I would like to stick each section in a html file and just include it. Unfortunately it seems like this is only possible with some nifty server side include techniques, with HTML5 (which I do not want to assume my users have), or with a nasty javascript hack where you copy your html file into js files with document.write calls for every line as written about here: Ways to include html in html.
What about something like handlebars.js or mustache.js? Can I use templating?
Since you don't want to use server-side includes, I would suggest using a static site generator (SSG).
If you are not familiar with SSG's, they allow you generate HTML pages from templates & includes (often Handlebars templates) and HTML, Markdown, JSON, or YAML, content using a CLI.
If you want to get started with an SSG, there are plenty of options, from Ruby based Jekyll, or Node.js based Assemble. In my opinion, Assemble is the best option and I would highly recommend it.

Are external javascript libraries hidden?

So I realize that anyone can view the javascript in-line with HTML running in their browser, so if I use an external js library on my server will its contents be completely hidden?
Another question is are there any cases where it's better to use in-line javascript, like with jQuery or something, or is there really no down side to just using a js library for all of it?
No, there is no way that your javascript will ever be "hidden". Anything that can be run in a browser can be trivially saved and inspected. The best you can do is use an obfuscator.
The downside to using an external file is that it's another request. The upside is that it can be cached independently. For best performance, code that will be used from more than one page should be stored in its own file, and code that is page-specific is better off being stored within the page that uses it.
JavaScript operates on the Browser level, that means that the browser at some point read your JS (external or internal same s.). You can easily conclude from this that if at some point the JS is now registered by the browser, and it's accessible by anyone with a bit more knowledge in web stuff. you'll not be able to hide your JS trickery.
Pus inside your JS a Copyright notice and pray.
Never send sensitive data through the yellow wire.
If you have some extra sensitive strings, encode and compare them on server side - sending them like MD5 or in some SHA model to the server.
Javascript, with the exception of something like node, operates client-side so you can't really use an "external js library" on your server, whatever that means.
Best practices dictate that you should almost always reference your javascript using <script> tags and link to your javascript file using the src attribute.

How to setup a dynamic website with javascript only (no serverside)

Here's my problem: I want to build a website, mostly static but with some dynamic parts (a little blog for news, etc..).
My webserver can only do static files (it's actually a public dropbox directory!) but I don't want to repeat the layout in every html page!
Now, I see two possible solutions here: either I create an index.htm page that emulates site navigation with javascript and AJAX or I create all the different html pages and then somehow import the layout bits with javascript..
From you I need ideas and suggestions on how to implement this, which libraries to use, or maybe there exists even something tailored exactly for what I need?
Thanks!!
I would define the site layout in your index.html file, and then use JavaScript and Ajax to load the actual content into a content div on the page. That way your content files (fetched by Ajax) will be more or less plain HTML, with CSS classes defined in index.html. Also, I wouldn't recommend building a blog in pure HTML and JavaScript. It wouldn't be very interactive; no comments, ratings, etc. You could store your blog content in XML and then fetch and display it with Ajax and JavaScript, however.
While on the subject of XML, you could implement all your site content in XML. You should also store the list of pages (for generating navigation) as XML.
Just another one way. You can generate static HTML in your computer and upload result to dropbox. Look at emacs muse.
jQuery allows you to easily load a section of one page into another page. I recommend loading common navigation sections into the different pages, rather than the other way around to avoid back/forward problems. Layout can be done with a separate CSS file rather than with tables to minimize the amount of repeated code. For the blog, you could put each blog entry in a separate file and load each section individually.
However, I would just use something already available. TiddlyWiki, for example, is a self-contained wiki that is all in one file. It's very customizable, and there's already a blog plug-in available for it. You can work on the site on your hard drive or USB drive, and then you can upload it to the web when done. There's nothing more to it.
Have you considered using publishing software on your computer to combine your content with a template, resulting in a set of static pages that you can then upload to the dropbox?
Some options in this regard come to mind:
Movable Type - can output static HTML which can then be uploaded to the server
Adobe Dreamweaver
Apple iWork Pages
To handle comments, you can use Disqus. It inserts a complete comment system into your site using just JavaScript.
You can use the Google Closure templates. It's one of the fastest and most versatile javascript templating solutions around.

best practice for dealing with common "structural" elements of pages?

Very basic question: I am coding a web app that has a handful of pages. These pages have the usual shared elements: eg, the site's header/masthead and a side-bar are present on all pages. The HTML is static (not dynamically generated, its "ajaxy-ness" is done client-side).
What is the best way of importing/"including" those common elements into my pages? The solution I am using is to have the HTML files contain empty place-holders
<div id="header"></div>
<div id="leftSideBar"></div>
(...)
and then do in jquery's $(document).ready():
$.get("header.html", function(html) { $("#header").html(html); });
// ....
Is this the best way to do this? I'm new to web development. : )
I guess I could also dig up a "macro-like" code-generation tool that I would run on the HTML files to replace, eg, "#header" with the contents of header.html. That way loading a page would require a single request for a single HTML file, which sounds better.
What is the smart way to achieve this? I am sure this problem has been solved a thousand times.
EDIT: The server-side is coded in Python+cherrypy. (I am assuming it is reasonable to try to keep away from dynamically generating HTML when doing "web 2.0-ish" web apps. Please correct me if I am wrong. As I said, I am very new to this environment.)
Thank you for your insights,
lara
If you want to include files, please consider using some backend language such as PHP or ASP. Javascript is not really meant to do this even if this would work.
<?php include 'other_file.php'; ?>
Using javascript to do this will lead, I think, to a poor SEO and the loading of the page might look weird for the end user. If you really don't want to use a backend language, some IDE have a way to handle templates, you could look into that.
Concerning frameworks, most of them have a way to handle templates. ASP.NET has the master page system, Ruby on Rails has layouts.
Here's an example using Rails :
<html>
...
<div id="content"> <%= yield %> </div>
...
</html>
Here all the content of a subpage will go into the "yield". Here's a link to learn more about that.
Some frameworks can handle multiple place holders.
To some extent, it depends on what you're using on the server side to render the pages. If your using server side scripts to generate the page you should be able to use a web framework (eg. Django or RubyOnRails) or even just a basic templating engine such as Genshi. Basic include functionality may even be built into the language you're using (ie. PHP)
If it's just static HTML you may want to look into setting up some form of server side includes such as Apache SSI or NGINX SSI. You'll need to pick the one that works with whichever server you're using, and you'll need enough access to install and configure the plugin or module.
Alternatively, you might want to look at using a script to generate your pages (edit, generate and deploy). A simple approach using cat / sed / awk / make (additional useful reference - Sed & Awk) may be all you need, or you might want to use a templating engine and a language such as Python or Perl.
I'd have the includes handled server-side, and this will mean fewer requests from the client, and may also have other benefits (easier to debug js, etc).
Having the server process includes really isn't going to put a major strain on it.

Where do you put your javascript?

Do you localize your javascript to the page, or have a master "application.js" or similar?
If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages?
EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/paste the jQuery source into their page but you never know.
Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering.
And yes, if one of the js files you are using is also hosted at google, make sure to use that one.
Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do.
All shared JS code lives in the SITE/javascripts directory, but it's loaded in 'tiers'
For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The script tags go at the top of the page.
There's also 'region-wide' stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags)
For less-shared stuff (say my library that's only needed in a few places) then I put a script tag in those HTML pages individually. The script tags go at the top of the page.
For stuff that's only relevant to the single page, I just write inline javascript. I try to keep it as close to it's "target" as possible. For example, if I have some onclick js for a button, the script tag will go below the button.
For inline JS that doesn't have a target (eg: onload events) it goes at the bottom of the page.
So, how does something get into a localised library, or a site-wide library?.
The first time you need it, write it inline
The next time you need it, pull the inline code up to a localised library
If you're referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library
If it's needed from more than one region, pull it up to a site-wide library.
A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view.
However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more 'super' js files for production situations.
I'd recommend using features like this rather than compromising the quality/readability of the actual source code.
Yahoo!'s Exceptional Performance Team has some great performance suggestions for JavaScript. Steve Souders used to be on that team (he's now at Google) and he's written some interesting tools that can help you decide where to put JavaScript.
I try to avoid putting javascript functions on the rendered page. In general, I have an application.js (or root.js) that has generic functionality like menu manipulation. If a given page has specific javascript functionality, I'll create a .js file to handle that code and mimic the dir structure on how to get to that file (also using the same name as the rendered file).
In other words, if the rendered page is in public/dir1/dir2/mypage.html, the js file would be in public/js/dir1/dir2/mypage.js. I've found this style works well for me, especially when doing templating on a site. I build the template engine to "autoload" my resources (css and js) by taking the request path and doing some checking for the css and js equivalents in the css and js directories on the root.
Personally, I try to include several Javascript files, sorted by module (like YUI does). But once in a while, when I'm writing essentially a one-liner, I'll put it on the page.
Best practice is probably to put it on Google's servers.
(Depends what you mean by "your" javascript though I suppose :)
This is something I've been wrestling with, too. I've ended up by using my back-end PHP script to intelligently build a list of required JS files based on the content requested by the user.
By organizing my JS files into a repository that contains multiple files organized by purpose (be they general use, focused for a single page, single section, etc) I can use the chain of events that builds the page on the back-end to selectively choose which JS files get included based on need (see example below).
This is after implementing my web app without giving this aspect of the code enough thought. Now, I should also add that the javascript I use enhances but does not form the foundation of my site. If you're using something like SproutCore or Ext I imagine the solution would be somewhat different.
Here's an example for a PHP-driven website:
If your site is divided into sections and one of those sections is calendar. The user navigates to "index.phhp?module=calendar&action=view". If the PHP code is class-based the routing algorithm instantiates the CalendarModule class which is based on 'Module' and has a virtual method 'getJavascript'. This will return those javascript classes that are required to perform the action 'view' on the 'calendar' module. It can also take into account any other special requirements and return js files for those as well. The rendering code can verify that there are no duplicates of js files when the javascript include list is built for the final page. So the getJavascript method returns an array like this
return array('prototype.js','mycalendar.js');
Note that this, or some form of this, is not a new idea. But it took me some time to think it important enough to go to the trouble.
If it's only a few hundred bytes or less, and doesn't need to be used anywhere else, I would probably inline it. The network overhead for another http request will likely outweigh any performance gains that you get by pulling it out of the page.
If it needs to be used in a few places, I would put the function(s) into a common external file, and call it from an inline script as needed.
If you are targeting an iphone, try to keep anything that you want cached under 25k.
No hard and fast rules really, every approach has pros and cons, would strongly recommend you check out the articles that can be found on yahoo's developer section, so you can make informed decisions on a case by case basis.

Categories