JavaScript Best Practices: where should I include my JavaScript? - javascript

I am building a website using PHP and JavaScript, and I feel that I have a good grasp on where to include my JavaScript, but a more specific situation has come up that has me confused. I currently have all of my JavaScript in one external file, which is being included on every PHP page.
Let's say that I have a paragraph with an id='myParagraph' and I need to highlight this paragraph in red with JavaScript on page load. This paragraph is only on ONE PHP page and my website has about 50 different pages. I immediately assumed that I should throw some code into my one external JavaScript file, something like:
$('#myParagraph').css('color', 'red')
and the paragraph would be highlighted when that page loads.
My question is: is this the best way to do it? To my understanding, every time I load a page it will be searched for an element with the id myParagraph, yet 98% of my pages won't even have that id. Is this wasteful? Should I instead include the following code:
function highlightParagraph()
{
$('#myParagraph').css('color', 'red')
}
in my one JavaScript file and then put some inline JavaScript in the PHP file with the id myParagraph to call the function highlightParagraph() when it's loaded? That way, only the one page with myParagraph will be searched and highlighted.
I feel like option 2 is the best, but I read all the time not to use inline JavaScript.
edit: I realize that for this example you would just use CSS. I'm just using it to get my question across

You should have a one "big" js file with the infrastructure functions and all the pages should have a reference to it.
Then each page should reference another js file with the functions related only.
The good things about using external js files are:
The files are cached after the first download => Faster surfing.
Separate of concerns, you keep the presentation tier away from the scripting tier.
Another important note:
The best way to change css is with css... not javascript.
I
If you change the element style on DOM ready, just add the element definition
#myParagraph{color: red;}

The problem with inline JavaScript is you might be starting with a few lines now, but in a few weeks or months, it will add up and be a lot of inline JavaScript.
That is bad, because inline JavaScript can't be cached by the browser like JavaScript files that you include with <script src="path/to/file.js" />.
That's bad because you add a lot of content that will be fetched every single page view by the user, adding load on your server bandwidth and slowing page load for the user.
If it's just a few selectors, don't worry; The time wasted on it won't cause any browser to sweat.
Though, if it becomes a lot of code for a different page/module of your site, you might want to split it into a different JavaScript file and include just that file when certain pages are loaded.
That way, the browser will cache that file and save that bandwidth for you and the user.

I wouldn't be too surprised if many people disagree with me (violently even) but I don't have a problem with putting a javascript tag with specific javascript for that page in the header if it will reduce the number of files or overall complexity of the project. Most of the core things that are done everywhere should of course be separated in another file but if it is a one page deal, then I would go for cleanliness.
The same goes for css, if it is specific to that page just put a css tag in the header with the specific changes that differ from the master css file. BTW as everyone is pointing out, this is a case where you want to just use CSS.

Related

Having same <div> on all my sites

I want to create a site like any other. I want the "thing" at the top (home downloads and stuff) to be on all my pages. Do I need to copy and paste the same code over and over again?
put the common part in your header/some specific file and use ,since you will be using header/some specific file on all pages so the desired content will also be loaded.
Learn Psd to html conversion For batter understanding the divs and styles modification and customization.. your divs and tags can be easily maintained with your stylesheet by giving id and classes you can also give one dive multiple classes and ids,
you are talking about master page i think
that is one in style and in that page you're showing other page, likely we can say one template page and many functionality see this and
see this
As far as I'm concerned pretty much all the intelligent options for solving this problem are mentioned in this question
Use a server-side template (e.g.php), use a client-side template (e.g. handlebars), use javascript, or you could use a static site generator like Jekyll.

Is it possible to convert a dynamic HTML page with a lot of javascript to a page without javascript?

I have a page with a lots of javascript. However, the page once rendered remains static, there are no moving things or special effects, etc... It should be possible to render the same HTML without any javascript at all using only the plain HTML and CSS. This is exactly what I want - I would like to get a no javascript version of the particular page. Surely, I do not expect any dynamic behavior, so I am OK if buttons are dead, for example. I just want them rendered.
Now, I do not want an image. It needs to be an HTML with CSS, may be embedded with the HTML, which is fine too.
How can I do it?
EDIT
I am sorry, but I must have not been clear. My web site works with javascript and will not work without it. I do not want to check if it works without, I know it will not and I really do not care about it. This is not what I am asking. I am asking about a specific page, which I want to grab as pure HTML + CSS. The fact that its dynamic nature is lost is of no importance.
EDIT2
There is a suggestion to gram the HTML from the DOM inspector. This is what I did the first thing - in Chrome development utils copied as HTML the root html element and saved it to a file. Of course, this does not work, because it continues to reference the CSS files on the web. I guess I should have mentioned that I want it to work from the file system.
Next was to save the page as complete with all the environment using some kind of the Save menu (browser dependent). It saves the page and all the related files forming a closure, which can be open from the file system. But the html has to be manually cleaned up of all the javascript - tedious and error prone.
EDIT3
I seem to keep forgetting things. Images should be preserved, of course.
I have to do a similar task on a semi-regular basis. As yet I haven't found an automated method, but here's my workflow:
Open the page in Google Chrome (I imagine FireFox also has the relevant tools);
"Save Page As" (complete page), rename the html page to something nicer, delete any .js scripts which got downloaded, move everything into a single folder;
On the original page, open the Elements tab (DOM inspector), find and delete any tags which I know cause problems (Facebook "like" buttons for example) (I also try to delete script tags at this stage because it's easier) and copy as HTML (right-click the <html> tag. Paste this into (replace) the downloaded HTML file (remember to keep the DOCTYPE which doesn't get copied;
Search all HTML files for any remaining script sections and delete (also delete any noscript content), and search for on (that's with a space at the start but StackOverflow won't render it) to remove handlers (onload, onclick, etc);
Search for images (src=, url(), find common patterns in image filenames and use regular expressions to replace them globally. So for example src="/images/myimage.png" => |/images/||. This needs to be applied to all HTML and CSS files. Also make sure the CSS files have the correct path (href). While doing this I usually replace all href (links) with #;
Finally open the converted page in a browser (actually I tend to do this early on so that I can see if any change I make causes it to break), use the Console tab to check for 404 errors (images that didn't get downloaded or had a different name) and the Network tab to check if anything is still being loaded from the online version;
For any files which didn't get downloaded I go back to the original page and use the Resources tab to find them and download manually;
(Optional) Cull any content which isn't needed (tracker images/iframes, unused CSS, etc).
It's a big job. I'd love a tool which automated all that, but so far I haven't found one. The pages I download are quite badly made (shops) which have a lot of unusual code, so that's why there are so many steps. You might not need to follow every step.

Placing Javascript in a HTML file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How bad is it to embed JavaScript into the body of HTML?
Ok, so I've been using JavaScript for a good while now and I'm no stranger to it, but my question is in regards to where the JavaScript should actually be placed in a HTML file.
I've always been told and worked under the impression that all of your references to external script files should be contained in the head tag and any script that is contained in the current HTML file should be at the end of the file.
Now, more recently and having discussions with co-workers I have seen more and more people placing script blocks in seemingly random places throughout the HTML page, such as
<div>
<p>Foo</p>
<script type="text/javascript">
//some script
</script>
<p>Bar</p>
</div>
Now is this good practice? I've always thought that it wasn't. If so, is it beneficial because the script gets executed at that point, but then why can't you wait until the rest of the HTML has been loaded?
+1 vote for at the bottom of the page
give visitors the;
content and markup first
then display with css
then ui with javascript
appreciate this is a tad high brow
Scripts should be placed at the bottom of the page, as that will allow all of the sites resources, such as images, to download in parallel. Once finished the scripts will then be downloaded, one at a time.
The reason it's better to place scripts at the bottom of the page, is because they block parallel downloads. Normally the browser downloads resources such as images in parallel, two resources at a time (as specified by the HTTP 1.1 specification), per hostname. Scripts stop this from happening and will not allow anything else to download until after they have been fully downloaded.
Duplicate of this Question
Is it bad practice to embed JavaScript into the body of HTML?
It is helpful (and perfectly valid) sometimes when you want to ensure that certain dom is created before the script is run.
When I use inline, It has an obvious benefit, for me. for example.
(I will try to explain it with basic scenario. so don't be critical about the scenario)
I have A,B and C html sections (divs) in my page. obviously I will render them all, but I want only one section visible at a time to a visitor. so I can't wait for the whole page and javascript files to be loaded and then apply the "set visibility priority for section" javascript method to fire. because in the meanwhile all three sections (A,B and C) will remain visible until everything is not fully loaded. and the page might look awful so I prefer to use inline javascript.
Started to write a comment underneath Rob Sedge's reply, but it grew larger...
1) CSS at top, in the header (unless you want the user to see page without styling, for large HTML files / external JS, where loading times can be extensive)
2) Content and markup in the body
3) JS in the footer, before </body>
Even though currently JS evaluation is strongly suggested to occur within $(document).ready, or $(window).load events, some external scripts might not do that - in such case they will be evaluated as soon as the content has been downloaded, often causing a random behavior. Furthermore , content is evaluated as soon as browser actually processes given tag (point 1), thus additional fun stuff.
An additional (and at least for me main) point is this - let's say that you've got a templating engine, or PHP inclusion in your documents. Now - let's say that you've got a lot of such files, and in one of them JS code needs to be changed. In such cases, if you're not the only person working on a project, you'd need to search for given bit of code in all of those files. Thus - keeping JS in one place is good practice.
Let's add to that, that if you indeed keep your JS code in one place, then such content can be minified or cached, allowing for faster loading of the site overall. Why indeed you'd want the user to download your bit of JS every time the page is loaded, when that script can be evaluated from the cache. If you separate your scripts, such approach becomes hard.
Basically, the scripts that you put on the header, are downloaded synchronously, and you can be sure that they ar going to be executed in order, but if don't need those scripts to be executed before the page finishes loading, maybe you prefeer to include them at the bottom, or in a deferred way, to finish render the page more quickly, and give the users a better experience.
About the scripts contained in the HTML, it depends on what they do. For example, if for some reason you need to do a Document.write, or you want to execute some code before the page is rendered, to modify the DOM, they are very handy.
I strongly recomend you to read the two books of Steve Souders: "High Performance Web Sites" and "Even Faster Web Sites", there you have a very good explanation on the differences.

page content in javascript needs to go in to html

I have links that when the user clicks them, the page immediately updates by utilizing the DOM, this is what my o2() does.
Problem is I want to seperate content from logic... i.e., i would prefer the content below to be in a .html file. Currently it is in a .js file.
My understanding is that it is good practice to keep structure/content seperate from logic... For example, using advanced registration for Javascript functions as opposed to inline registration.
How do I get the html content below into a .html file?
function l1() {
o2('Ac1_3','<br/><p class="h">ALL YOUR BOOKMARKS IN ONE PLACE</p><img class="i1" src="i3.jpg" alt=""/><img class="i1" src="i4.jpg" alt=""/>');
}
If you're dynamically adding stuff to the DOM using JavaScript, there is no way around keeping that content in the JS file, unless you want to get pointlessly complex.
Personally, I think it's fine to mix content and logic a little, like this, just don't go over the top to the point where it gets confusing.

Adding style and script tags to body acceptable?

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.

Categories