why can't a css file be included in a .js?
in other words, why can't <style></style> syntax be included in a .js file? the js script and css works on my page when where are in the header but when I call them externally, the css fails?
People who implemented <script> and <style> 15 or 20 years ago decided not to do that.
Things moved very, very fast in the 90s, in some ways at least.
Note that JavaScript pre-dated CSS by a couple of years. They were developed and driven by different companies. By the time CSS was invented, modifying browser JavaScript parsers to understand CSS blocks was a very unlikely thing to happen (and, in fact, it didn't).
Here's a guess: you moved one or more <script>...</script> blocks along with one or more <style> ... <style> blocks into a single file, and then tried to import it with a <script src="something"></script> tag. That won't work. Your external JavaScript and CSS files need to be pure JavaScript and pure CSS.
Because you cannot style javascript, styles apply for html tags. If you include a style tag in a javascript file, what would the styles apply for?
I don't know of any way of including pure css in to a .js file, But there's an alternative.
You could use #getElementById().style.
Its not really practical but it's the only way that I know of.
There are several reasons:
Cascading StyleSheets are describing how things look on your web page whereas JavaScript describes how things behave – they are used for completely different things.
Websites should work without having JavaScript enabled. At least that's what I learned in the early days. If you included straight CSS in your JavaScript and the browser had JavaScript disabled then you wouldn't see those styles applied.
A .js file only contains Javascript. It's not an HTML file, so it isn't parsed for any kinds of <tagname> codes. You can't put <style> in it for the same reason that you don't surround the code with <script>...</script> inside the file (if you do this you'll get an error, because it's not Javascript). The contents of the file are treated like the contents inside a <script>...</script> block, and you're not allowed to put <style> in there, either -- it's only script code.
Related
I need to implement javascript and css resources for the framework I'm working on, but I have a BIG concern.
If you take a look at current websites like Facebook, Google, Youtube and other top-tier sites, their source code show their usage of javascript in various places in the code. The first question coming into my mind is... isn't supposed for javascript source files to be allocated at the beginning of the document? You can/should be able to place javascript commands enclosed in script blocks, but... source files, too??
The books I've been reading suggests (as best practices, I guess) all source files should be allocated in the head section, while displacing all code blocks to the end of the page, right before closing the body section (when possible).
Same applies for CSS. I've seen pages where, in the middle of the page, you find a source file inclusion, while the normal declaration is to include all css files in the beginning (as it's more efficient than in-place inclusion because they load in parallel that way).
In my thoughts, and if I'm to follow the books I've been reading, source files (both javascript and css) go always on top, script blocks (when possible) go to the bottom part of the document and CSS inclusions are to be avoided in-place (except for when you want to use the scope attribute or it's a style declaration inside an html tag, which should also be avoided when possible).
Is that right?
Best practice dictates thus:
CSS files should go into the <head> of the document, as near to the top as possible. I usually place mine after any <meta> tags.
JavaScript files should go as close to the end of the <body> as possible, usually directly before the </body> tag.
This is because JavaScript files load serially and are blocking, so if JavaScript files are included in the <head> of a page, all files must load in their entirety before the main body of the document can load, which often creates the perception of a delay.
Really, there is little difference between JavaScript files and JavaScript script block. They both use the <script> element, it's just that externally referenced files have an src attribute. From the point of view of the parser, they are the same.
From a validity point of view, <script> elements may be placed anywhere in the <head> or <body> of a page, and there are times when <script> files should go in the <head>, such as when using something like typekit, as this will ensure font files are loaded in time for the fonts to be displayed as soon as the page has loaded, preventing a FOUF (flash of unstyled font)
Lets say I put the following in <body>
<script src="https://gist.github.com/2059.js"> </script>
looking at that js file, the first line is:
document.write('<link rel="stylesheet" href="https://gist.github.com/stylesheets/gist/embed.css"/>')
I don't have write permission to that js file. Is it possible to dynamically swap out embed.css and swap in the href to another version of that CSS file? Can this be done such that it requires no user input - the page will load with my own CSS file and not embed.css?
The easiest option here is going to be to load your own CSS in a way that will override the Gist CSS - this is going to be much simpler than trying to dynamically change the code Gist provides. Two options for this:
Add !important to your CSS declarations.
Use the same selectors as the Gist CSS, but prefix them with another selector to make them more specific than the Gist CSS declarations, e.g. mycontentarea .gist-syntax .c
The second option is probably going to be more reliable, as long as you know a selector for an enclosing element. See a working example here (I've replaced the standard Gist string color with a nasty yellow): http://jsfiddle.net/aqGEc/
NOTE: I am in no way advocating multiple heads within a page
I'm using Apache Tiles and I have a few tiles that include their own heads. The result of the Tiles renders into an HTML page with multiple heads.
My questions:
How is the resulting page handled in IE and Chrome? [It renders and appears successful]
WITH APACHE TILES What is the best practice for dealing with/avoiding multiple heads [for CSS/Javascript] without having to demand all pages use the same JS and CSS files.
For Example with Question Two:
Lets say you have the following pages: home, profile, and gallery listing. Gallery listing has fancy JQuery+YUI+... and more styles. For most users, they would only be interested in the home and profile pages, so why slow them down with loading the JS and CSS files associated with Gallery.
This is what is generated
<html>
<head>
<title>The Template's Title</title>
</head>
<body>
<head> <script src="javascriptfile.js"/></head> Tile One Content
<head> <script src="javascriptfile2.js"/></head> Title Two Content
</body>
</html>
The generated contents is running the script in javascriptfile.js, and javascriptfile2. What I'm asking in the first question: is the extra heads ignored, and the contents considers? are they combined into the html/head level? Is it possible to include CSS files in the second or later head? Will this create an error with a stricter DTD?
Well, in modern Chrome, it's at least possible to know what happens. Chrome uses the HTML5 parser algorithm which describes exactly how invalid mark-up is processed. The gory details are at http://dev.w3.org/html5/spec/tree-construction.html#parsing-main-inbody
What happens in your example is that the first <head> in <body> is discarded. Then the <script src="javascriptfile.js"/> tag is processed, which is a start tag, not a self-closing tag, so everything that follows, including everything that looks like a tag, becomes a text child of the script element. Nothing is displayed and no script is run. If <script src="javascriptfile.js"/> is replaced by <script src="javascriptfile.js"></script>, and ditto for <script src="javascriptfile2.js"/>, the head start and end tags are silent discarded, and the script elements are not moved. "Tile One Content Title Two Content" is displayed and the scripts are run. The DTD makes no difference at all.
IE is somewhat trickier to know, as before IE10, it doesn't use the HTML5 parser algorithm and therefore it's exact behaviour is a mystery. However, a cursory experiment appears to show that it has the same behaviour as described above.
Although some legacy browsers move elements that can only appear in the head - such as <link> - into the head, other browsers do not, and no such behaviour can be relied upon.
All in all, best steer well clear of such constructs.
I don't know about practices for Apache Tiles.
What is the purpose of doing something so egregiously invalid? And why you're asking this seems very unclear.
Not only should you only have ONE <head></head> section on a page, under no circumstances is the <head></head> to be nested anywhere inside the <body></body> section.
This practice makes absolutely no sense whatsoever....
(Side-note: Certain browsers ignore or move invalid tags when the DOM is constructed which will defeat your entire purpose of doing this.)
EDIT (based on comments):
For anyone interested in including <script> tags within the <body>, you can read more about the specific details in my answer here...
Will linking javascript files in the body rather than in the header cause a problem?
You don't really need extra heads to include additional css/js. You can 'inline' the whole <style type="text/css">...</style> part and it will render fine. Will it validate? No. But will run fine.
How is the resulting page handled in IE and Chrome? [It renders and appears successful]
I don't know and I really don't want to know.
What is the best practice for dealing with multiple heads [for CSS/Javascript] without having to demand all pages use the same JS and CSS.
Don't do it :-)
Is there a reason you can't just include the JS files in the body / head without the extra tags?
Or add the css / js files in the 'normal' head section of the document (where it should be).
Well atleast you want the CSS files to be loaded as soon as the page starts loading. JS files can (sometimes) be loaded at the end of the HTML.
For example if the JS files need to have a completely loaded DOM (for e.g. accessing DOM elements).
Note
Sorry this isn't really an answer to your question, however what you are doing just looks way bad. :) And is almost certainly not needed / there will be a better solution for it.
I'm creating an AJAX heavy web application and I'm curious on what people's thoughts are on adding style and script tags to the body of an HTML document.
I've been using the jquery.load() method to insert content on the fly. An example partial HTML page that could get loaded into the body element is this:
<script type="text/javascript">
$(function() {
// All required java script for the control goes here...
});
</script>
<style type="text/css">
/* All required styles for the inserted HTML go here */
</style>
<div id="some-control">
<!-- Required HTML markup is here. -->
</div>
Since this HTML is getting loaded into a DIV, we are ending up with script and style tags that are not in the head but in the body of an HTML document. I'm not sure if this is valid HTML? Is this a common approach to developing AJAX enabled web applications? Are there any drawbacks I should be aware of?
As far as Javascript is concerend, you can put it any where on the page provided that elements it will work upon are loaded before and it does not throw the error undefined element. Famous Yahoo performance article and even Google (in terms of SEO) suggests to put javascript at the end of the page just before the </body> tag.
If you can manage to put your script just before </body> tag, that is considered good approach otherwise what you are doing now should be fine if everything is working properly for you.
I would actually disagree with Sarfraz and say that you should avoid using <script> and <style> tags in your page body as much as possible. The advantages of moving your JS to an external file are endless. The most obvious include:
leveraging on browser caching - if you just write code in your body, that's extra kilobytes of data that need to be loaded for every page. If it's a universal function, you're wasting precious load time. If it were in an external file, most modern browsers cache that file and only request a new version so often. This decreases server load as well (less requests)
Furthermore, if you ARE using a similar script on multiple pages, what happens if you need to make a change :(. Now you're running around searching for every instance of a <script> tag to make a change. Having all your code centrally located and universal allows for ONE change and DONE
Versioning - if you use version control (GIT, SVN, etc), it's much easier to track and revert one file (if you made a mistake or accidentally lost code) than all of them
CSS share a similar story. Again, with caching and centralized storage, and reusability. It's even more important, however, for styles to match on a website. From a UI standpoint, you don't want your fonts changing from page-to-page and you don't want to edit 40 pages every time you want to add a new style.
As far as having the JS in the document because you are using AJAX loaded content, I suggest you look into .bind and .live. They let you attach handlers to existing and future instances of a DOMObject. For example:
$('.class').live('click', function(){
alert('I was clicked!');
});
This will apply to any object that existed at page load AND objects that are later created. The following code will NOT - it only applies to objects created on load:
$('.class').click(function(){
alert('I was clicked!');
});
When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.
Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.
If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.
Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.
As JavaScript in blocks HTML rendering, and it's good practice to keep JavaScript at bottom, just before closing body tag , is it not the case with CSS also?
I know we can't keep external CSS outside .
CSS does not block in the same way JavaScript does
To quote Yahoo's Developer Network Blog
With stylesheets, progressive rendering is blocked until all stylesheets have been downloaded. That’s why it’s best to move stylesheets to the document HEAD, so they get downloaded first and rendering isn’t blocked. With scripts, progressive rendering is blocked for all content below the script. Moving scripts as low in the page as possible means there's more content above the script that is rendered sooner.
In addition, when CSS is added to the head, it is parsed first, and results in the HTML being styled even as it is downloaded. This avoids the Flash Of Unstyled Content that happens if you place style tags at the bottom of a large page of HTML.
Not only does CSS not block the way Javascript does, but also some browsers will do strange things if you put CSS anywhere but the <head>, like ignore it, or apply it incompletely. HTML5 actually prohibits <style> from appearing outside <head> (except with the "scoped" feature, which AFAIK nobody implements yet).
CSS stylesheets are loaded using the <link> element, this element is only valid when it is in the head of the document. As for CSS blocking HTML rendering, this isn't the case because the CSS is applied once the browser is loaded just like the other <link> elements. JS blocks HTML because the browser assumes the JS wants to take control and actually do something before loading the DOM fully, basically JS is executed and then left alone.
Think about it, if CSS was loaded the same as JS, no element would be styled because it would be referring to elements not yet loaded, therefore it is applied afterwards and doesn't block loading.
No, css is apply to DOM element right after the browser read the css.
In case of javascript you can keep the script at read, since you make it run after all html loads, like:
window.onload = function (){
//here we start
}
JS
Since JS can change your web page (modify the DOM) browsers wait for all external JS to be downloaded (parallely), interpreted and executed before continuing with the rest of the HTML that comes after <script src="..." >
Therefore it's a good practice to put all external JS at the bottom of the <body>. This way your HTML gets parsed and rendered and your user has a feeling that something is happening...
CSS
CSS on the other hand cannot change the DOM, cannot make any "heavy" changes on the page and that is why the browser doesn't block download, parsing of the rest of the HTML, and progressive rendering as is case with the JS. It seems that it does block the rendering, but it is still better to put it at the top and avoid the long FOUC . It doesn't block download, though
Now, seems that with the rise of mobile devices putting your CSS to your HEAD and JS at the bottom is not enough... You will want to put the ATF (above the fold) CSS inline and the rest of your huge minimized CSS together with your JS - at the bottom / defered and async
Take a look at this: http://addyosmani.com/blog/detecting-critical-above-the-fold-css-with-paul-kinlan-video/
Why would it be a good practice to keep Javascript at the bottom?
I'd say that it's best practice to put CSS as well as Javascript in separate files and include them in your HTML document using the <head> section.