organise javascript code based on page - javascript

Hi I am relatively new to javascript development. At the moment I have a single javascript file with lots of little misc bits of code that get called in different part of the website. For example I have an event handler for some google maps stuff that is only called on 1 single page, I have some validation stuff for my contact page etc etc. My question, is how best to organise this code - given that each page only requires very little code but its different and specific per page?
Oh, I am using jquery if that makes a difference.

If there is nothing shared by each page from your js file and only a part of it is used by each page, the good way will be to separate each of those js code snippets for each page. This will simply improve page loading a little depending on the size of your javascript file.

Related

adding javascript to wordpress pages

I got thrown at a project that is using Wordpress for generating websites. Once done, the team takes a copy of the generated static html code and puts it on some webhosting platform as a standalone website.
I am now asked to add some function adding dynamic behavior to a page by calling a webservice and add some of its data to that page.
I tried adding javascript using the custom html widget of the Gutenberg editor but it does not work well. I could make it work for simple things but firing a request did not work and it is hard to debug.
Wondering, is a plugin the right way to go for or are there better ideas?
I assume it needs to be some some php code adding javascript contained in html I guess?

If grouping front-end code helps reduce requests, why aren't more websites written on one html document?

I guess what I'm asking is that if grouping JavaScript is considered good practice, why don't more websites place the JavaScript and CSS directly into one HTML document?
why don't more websites place the JavaScript and CSS directly into one HTML document
Individual file caching.
External files have the advantage of being cached. Since scripts and styles rarely change (static) and/or are shared between pages, it's better to just separate them from the page making the page lighter.
Instead of downloading 500kb of page data with embedded JS and CSS, why not load 5kb of the page, and load from the cache the 495kb worth of JS and CSS - saves you 495kb of bandwidth and avoids an additional 2 HTTP requests.
Although you could embed JS and CSS into the page, the page will most likely be dynamic. This will make the page load a new copy all the time, making each request very heavy.
Modular code
Imagine a WordPress site. They are built using a tom of widgets made by different developers around the world. Handling that many code stuffed in one page is possible, but unimaginable.
if some code just short circuited or just didn't work on your site, it's easier to take out that code linking the external file, rather than scouring the page for the related code and possibly accidentally remove code from another widget.
Separation of concerns
It's also best practice to separate HTML from CSS and JS. That way, it's not spaghetti you are dealing with.
When you have a lot of code in a single document, it's harder to work with the code because you need more time to find the necessary string to change.
That is why it's good practice to divide code into separate files, with each of them solving its own special task, and then include them in code where it's necessary.
However, you can a write script which will join your files from the development version, which has many files, to a release version, which has fewer files, but this brings two problems:
People are often lazy to do additional coding to create this script and then change it when the structure of your project becomes more complex.
If you find a bug or add a small feature, you will need to rebuild your project again both in developed and release versions.
They separated them so that multiple webpages can use the same file. When you change a single file, multiple pages can aromatically updated also. In addition, big HTML file will cause a long time to download.

Separating JS & HTML in Wordpress

I recently read the discussion https://stackoverflow.com/questions/62617/whats-the-best-way-to-separate-php-code-and-html
I am facing a similar dilemma.
Currently working on a WordPress website which has a LOT of sliders, animated dropdowns, forms and other components. Each of component is used multiple times throughout the website, so I've created a PHP file for each of these components and I use include to insert them wherever they are required.
Now the file I am including contains HTML & JS {for initializing control}
And finally when I looked at the generated html page in browser, it was chaotic! HTML & JS mixed everywhere!
I wanted to know if its better to include everything in one big JS file and include it on top of every page or its more efficient to have small JS blocks in the section?
In my opinion, if the HTML/JS is valid, there's nothing wrong with it being a bit messy - the end user will never see it anyway. As for what's best from a design point of view, it really depends on the situation.
Personally, I think it's alright to have a big JS file that's included in every page, but some people prefer to output the code in small blocks where it's needed. Ultimately, it really depends on what the program is and what works best for you.
If the JS code is targeted to just a particular section or page i think it is better to include it in page itself instead of a separate file but if it is meant to be used in multiple places then use a separate file as it will also be easier to maintain it that way.

Javascript and website loading time optimization

I know that best practice for including javascript is having all code in a separate .js file and allowing browsers to cache that file.
But when we begin to use many jquery plugins which have their own .js, and our functions depend on them, wouldn't it be better to load dynamically only the js function and the required .js for the current page?
Wouldn't that be faster, in a page, if I only need one function to load dynamically embedding it in html with the script tag instead of loading the whole js with the js plugins?
In other words, aren't there any cases in which there are better practices than keeping our whole javascript code in a separate .js?
It would seem at first glance that this would be a good idea, but in fact it would actually make matters worse. For example, if one page needs plugins 1, 2 and 3, then a file would be build server side with those plugins in it. Now, the browser goes to another page that needs plugins 2 and 4. This would cause another file to be built, this new file would be different from the first one, but it would also contain the code for plugin 2 so the same code ends up getting downloaded twice, bypassing the version that the browser already has.
You are best off leaving the caching to the browser, rather than trying to second-guess it. However, there are options to improve things.
Top of the list is using a CDN. If the plugins you are using are fairly popular ones, then the chances are that they are being hosted with a CDN. If you link to the CDN-hosted plugins, then any visitors who are hitting your site for the first time and who have also happened to have hit another site that's also using the same plugins from the same CDN, the plugins will already be cached.
There are, of course, other things you can to to speed your javascript up. Best practice includes placing all your script include tags as close to the bottom of the document as possible, so as to not hold up page rendering. You should also look into lazy initialization. This involves, for any stuff that needs significant setup to work, attaching a minimalist event handler that when triggered removes itself and sets up the real event handler.
One problem with having separate js files is that will cause more HTTP requests.
Yahoo have a good best practices guide on speeding up your site: http://developer.yahoo.com/performance/rules.html
I believe Google's closure library has something for combining javascript files and dependencies, but I havn't looked to much into it yet. So don't quote me on it: http://code.google.com/closure/library/docs/calcdeps.html
Also there is a tool called jingo http://code.google.com/p/jingo/ but again, I havn't used it yet.
I keep separate files for each plug-in and page during development, but during production I merge-and-minify all my JavaScript files into a single JS file loaded uniformly throughout the site. My main layout file in my web framework (Sinatra) uses the deployment mode to automatically either generate script tags for all JS files (in order, based on a manifest file) or perform the minification and include a single querystring-timestamped script inclusion.
Every page is given a body tag with a unique id, e.g. <body id="contact">.
For those scripts that need to be specific to a particular page, I either modify the selectors to be prefixed by the body:
$('body#contact form#contact').submit(...);
or (more typically) I have the onload handlers for that page bail early:
jQuery(function($){
if (!$('body#contact').length) return;
// Do things specific to the contact page here.
});
Yes, including code (or even a plug-in) that may only be needed by one page of the site is inefficient if the user never visits that page. On the other hand, after the initial load the entire site's JS is ready to roll from the cache.
The network latency is the main problem.You can get a very responsive page if you reduce the http calls to one.
It means all the JS, CSS are bundled into the HTML page.And if your can forget IE6/7 you can put the images as data:image/png;base64
When we release a new version of our web app, a shell script minify and bundle everything into a single html page.
Then there is a second call for the data, and we render all the HTML client-side using a JS template library: PURE
Ensure the page is cached and gzipped. There is probably a limit in size to consider.We try to stay under 400kb unzipped, and load secondary resources later when needed.
You can also try a service like http://www.blaze.io. It automatically peforms most front end optimization tactics and also couples in a CDN.
There currently in private beta but its worth submitting your website to.
I would recommend you join common bits of functionality into individual javascript module files and load them only in the pages they are being used using RequireJS / head.js or a similar dependency management tool.
An example where you are using lighbox popups, contact forms, tracking, and image sliders in different parts of the website would be to separate these into 4 modules and load them only where needed. That way you optimize caching and make sure your site has no unnecessary flab.
As a general rule its always best to have less files than more, its also important to work on the timing of each JS file, as some are needed BEFORE the page completes loading and some AFTER (ie, when user clicks something)
See a lot more tips in the article: 25 Techniques for Javascript Performance Optimization.
Including a section on managing Javascript file dependencies.
Cheers, hope this is useful.

javascript basic question

While declaring Javascript in a html document. We have 3 ways to do that
script section goes in the head tag
script section goes in the body tag
javascript is references from an external file
Which one of these is faster and efficient with respect to performance is considered?
Thanks
Put javascripts/references to linked scripts at bottom of page if possible. As suggested here: http://developer.yahoo.com/performance/rules.html
1 and 2 are about tag location. 3 could apply to both 1 and 2.
In addition, you can have javascript in event handler attributes, like so:
<button onclick="alert(1)">pressme</button>
to top it off, you can also have javascript as url, in for example links:
click me
Just sticking to your examples: first of all, it is usually a good idea to use external script files that you load with a src component in tags. This allows the browser to cache the script, which allows the page to load faster after the initial page load. this is especially true if you use things like jQuery and load them from a public Conent delivery network (like the google ajax api see: http://code.google.com/apis/ajaxlibs/documentation/)
As for the location (head or body): in the olden days, people used to say, put your scripts in the head to ensure they are loaded once the body is loaded and all the interactive elements can be used by the user. But the problem with that is that the loading of those scripts will block loading of the visual part of the page, the body. Basically, the users are looking at a blank page, wondering whuy their page is taking so long to render.
So nowadays, the popular wisdom is to put all scripts as far down in the body as you can, and make sure that you write your javascript in a way that it can handle partially loaded scripts. The YSlow guide is a great resource to learn about these things. see:
http://developer.yahoo.com/yslow/help/
It really depends on what type of JavaScript you are writing. If you writing code that needs to be executed in the body (for ex: document.write()) you will have to write that in the body tag. If that is not the case and if you are writing javascript functions then should go in the head tag or in a different file. You would use a different file if you are going to use the same functions across many pages.
w.r.t performance, it again depends on what you are doing. If you have just one page that uses javascript, it would be faster to keep it in the header. This way you would reduce a round trip to get the javascript file.
If you have multiple pages that use the same functions, then it will be faster if the functions are in a different file because they will be downloaded once and used multiple times.
I'd say it depends on the circumstances.
An external file is a good idea if you have a large script that is used across a site and you want to take advantage of client-side caching mechanisms.
If a script is only used on one page then keeping it in the head/body might make sense. Clearly the earlier the script comes in the page the sooner the JavaScript will be executed, but you may be constrained by waiting for the DOM to be available to the script anyway, in which case it won't make any difference if it's in the head or the body.
You could put the script immediately after any HTML that defines the DOM that it needs access to. This would probably be the quickest way of getting a script to execute in the page, but don't go for this over an externally loaded (and cached) file if it is large or used in many places.
If you're super concerned about performance, I would say loading the js in the html would be fastest. Items in the load before the rest of the page, so from a user's perspective, they may think the download takes longer with js since the page won't start to render until after the is loaded, but the amount of data should be the same. External js file is likely the slowest since it will require a separate http request.
The short answer is...well...it depends.
If by
faster and efficient with respect to performance is considered
you mean "loads faster", then inline script in the head will get your code into the browser faster the first time it's loaded. An external file can be cached, so if you're including the same script in multiple pages, once you overcome the overhead of loading it the first time, then you have it resident in memory.
I prefer to have my Javascript and HTML all in the same file just because I don't like having a lot of different tabs open. But then again it is a lot neater to use your Javascript, HTML, and CSS all in different files.
So far, the more complicated/long the code is, I'd use a different file, but if the code is simple, I'd just use the same file for everything.

Categories

Resources