Easy way to load custom javascript files on a webpage? - javascript

I am working on a project where the Javascript is getting out of hand, so I've done my best to put each object into a different file (within reason of course... I sometimes group related objects and put them in one file if they are small).
One thing I am honestly having trouble with is managing the dependencies of these objects. Javascript doesn't seem to ways to include/declare dependencies... and I am honestly finding this really very annoying.
What's worse is that I have to put these dependencies into the separate html files which they are used. After including so many script tags at the bottom of so many pages, this has become an absolutely pain to manage. Here is an example:
<script src="${base}/js/ui/autoCompleteWidget.js"></script>
<script src="${base}/js/pagelet/addStudentToStudyGroupForm.js"></script>
<script src="${base}/js/pagelet/studentListing.js"></script>
<script src="${base}/js/pages/studyGroups.js"></script>
This is bad enough, because many of the first dependencies are declared over and over as they are needed on various pages. What is worse though is having to introduce 1 more dependency somewhere in the middle at a later point in time... and then having to go through my entire project and inject that one script tag over and over on each page where it is needed. Since there is no compile time warning on HTML markup... if I forget to do this on one page... the page simply won't work. Something like this is hard to automatically test and there's no way for me to know unless I check each page that uses Javascript.
I was wondering... what is easiest/most painless way to load these scripts? Like, what is the standard way to do it that robust, easy to do, etc.?
Thanks

You might want to look into libraries such as http://requirejs.org/ which can take some of the pain out of this type of situation.

Related

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.

Organizing library dependencies in JavaScript best practice

What are peoples thoughts on the best way to organize dependencies in javascript? I know the basics but have some more specific questions. From reading Douglas Crockford and other posts around here, I know to put script tags as late in the body as possible,use minifying, combining all the client-side code into one .js file where applicable, etc.
What is the best way to use libraries though? Say for instance you do the following:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="somelib.min.js"></script>
<script type="text/javascript" src="myappcode.min.js"></script>
Could this be considered too many script tags? Say that myappcode.min.js is dependent on but also modifies certain parts of somelib.min.js -- should you just combine those into one file?
Also is it possible or even a good idea to reference one .js file such as a library inside another .js file, as opposed to just putting one script tag before another in order to reference it in the latter? Coming from a C# background I know that JavaScript is parsed sequentially as opposed to starting in a main() method and proceeding -- so I am guessing the script approach is pretty standard, but wanted to make sure.
You can merge those JavaScript tags into a single tag while still being able to keep all the JS library files separate if you write a JavaScript handler. Check the code for the JS handler in the UC Mobile Web Framework for an example of how you might do this.
It depends on the person looking at it. I don't think 3 script tags is bad, although it's known that reducing the number of HTTP requests improves a websites loading speed (as it decreases the overhead of each individual request).
I would not merge files just for the sake of merging them in my development project. When uploading to a production server however, I'd merge the files together to reduce the number of script tags necessary as you shouldn't care about readablity/etc in a production environment.

Only running javascript required for current page, best methods?

So I know it's best to have one javascript file for an entire site to limit http requests. So obviously only some javascript is required for some pages. What is the best way of only running the javascript required for the current page?
EG.
if(page=='home'){
//run javascript require for the home page
}
Maybe this isn't an issue and if targeting elements are not found on the page javascript will just fail gracefully? I would just like to know the best practice for this javascript structure.
Encapsulate your logic in functions. Then just call the function(s) you need in each page, either via "onload" or an embedded function call in the page:
<script type="text/javascript">
yourFunctionForThisPage();
</script>
Edit: Just to clarify: my answer is assuming the (implied) constraint of a single .js file. As others have pointed out, although you save on HTTP requests, this is not necessarily a good idea: the browser still has to parse all the code in the file for each page, whether used or not. To be honest it's pretty unusual to have a global site-wide js resource with everything in it. It's probably a much better idea to logically split out your js into various files, i.e libraries. These libraries could be page-based - i.e specific code for a particular page, or algorithm/task-based that you can include in whatever pages need them.
Is this feasible?
While it is best to have just a single Javascript file per page to lower the number of requests yet it may not be feasible. Especially the way that you'd like to do it.
If you're asking how to join various scripts of various pages into a single script and then running just those parts that are related to a particular page then this is something you shouldn't do. What good is it for you to have one huge file with lots of scripts (also think of maintainability) compared to a few short integrated scripts? If you keep the number of scripts low (ie. below 10) you shouldn't be to worried.
The big downside is also that browser will load the complete script file which means it will take it more time to parse them as well as consume a lot more resources to use it. I'd strongly suggest against this technique of yours even though it may look interesting...
Other possibilities
The thing is that the number of Javascript files per page is low. Depending on the server side technology you're using there are tools that can combine multiple script files into one so every page will just request a single script file which will combine all those scripts that this particular page will use. There is a bit overhead on the server to accomplish this task, but there will be just one script request.
What do you gain?
every page only has scripts that it needs
individual script files are smaller hence easier to maintain
script size per request is small
browser parsing and resource consumption is kept low
Know what you will need on the page and use a script loader like labjs.
Also, remember that your specific case might be different from what others have found, so you might want to do some tests, to verify if, for example, having 5 little files, is better (or worse) than 1 big file.
The only way to be sure is to test different options yourself and come up with a fitting solution.

Structure with Javascript code? CSS, Divs and then Scripts?

I have noticed that the place of scripts is not irrelevant, if script refers to some div below, it may not work, not sure about rules perhaps my messy code assign some other value later. So I am asking general guide-lines to design the structure in Javascript code. What is the order for example to the parts such as CSS, Divs and Scripts?
My personal bias is that good code should be easy to read from the bottom to the top. So, for example, a browser could have browse() script at the bottom to start browsing and the rest junkies that it uses to to top in logical order, so after browse() its above script should be something that the browse() uses. Field values should be defined at the top, I think things like CSS and divs -- rude analogy I know. But if user's browser is slow, the script may not execute at all and the code seems to be non-working. Dilemma between practicability and readability.
Please, define terms, such as top-to-bottom coding and bottom-to-top coding, and show the structure.
In head, put CSS, then scripts in order of usage and in body Divs.
Example if you use jQuery and have a .js file that uses jQuery code, it's adviced to import the jQuery files before your .js
Personally I try to avoid putting scripts in the body and rarely face such issues as scripts not finding divs below.
Usually I try and place scripts that manipulate DOM on the bottom of the page, it solves the problem of not finding the DOM elements before a page is fully loaded.
However, libraries (such as jQuery) should go in <head>.
You can consider the entirety of the page, JavaScript, CSS, and HTML, as a combination "top to bottom" generic program, where later code can reference earlier code. Because when the page loads, it simply starts "executing" or interpreting "code" as it sees it. Most of the time, that "code" is simply definitions (like JS vars or functions), and placement of elements (like DIVs).
However, if you have JS that actually runs during load, that is code, that is outside of a function definition, then it's going to only "see" things that exist before the code is executed. So, in that sense, the whole thing is simply one long program, with the HTML as a meta-language building a DOM as the HTML is interpreted by the browser.
Obviously there are techniques to run code at certain points, like page load, etc., and that's where the libraries like JQuery come in to to expose those event points and make them easy to use.
But fundamentally, it's a top down script, like pretty much anything else.
I try not to have excessive script block ins my code at all. I call all external scripts in the head or just before body close in the case of some api inclusion (addthis for example). All inline scripting goes in a single block at the just before the close of the body tag as well.
RequireJS - Outsourcing Script Loading
I have found RequireJS particularly useful for JavaScript application development. In my case I'm dealing with tens of JavaScript files (modules) but I'm sure it will come in handy in other cases as well.
The library handles a lot of boring stuff for you. All you need to do is to set up some files (main.js, build options), state module dependencies and you are good to go. It includes a build system so you can easily get a debug or production build (minified) done.
On Application Structure
I like to code "top-down". The idea is that higher levels of an application should be really loosely defined. You shouldn't see actual algorithms used for solving some specific problems there. The highest level should be just about wiring parts of an app together. The lower levels solve more specific problems till you get to concrete implementations.
This is a fairly standard, layered approach to application development. You probably won't need something like this for casual scripting. It's still a good idea to apply in practice as it helps you to compose your scripts better. You can use the idea on closure level even to make the code easier to read.
On Functions
It might help to read "function" as "to" (Logo concept :) ). I think a well-written function reads like a recipe (to "drawLine" you must do this and that using these parameters...).
I know this might not be exactly pertinent to the question but I thought it might be a fun idea to mention. Perhaps it will help you to see functions differently and help you to structure your JavaScript code that way.
On Elements Not Ready
Considering elements not ready and script loading... you might be better off defining your code at a "document ready" handler. This is fairly standard thing to do.
If you use RequireJS or a similar library you probably don't have to worry about this. They handle this particular issue for you.
The style sheets go first and scripts go later. The reason for this is scripts are "blocking", meaning that while the browser is downloading JavaScript, it will not download anything else - not style sheets, nor images.
Browsers will only download so many resources at one time, and will block all other loads until this number of resources free up. IE8 actually will download quite a few at a time, as many as 18 or more. Firefox and Safari will download 6 at a time, but IE6&7 will only download one script or two non-scripts at one time. The thing to keep in mind is these resources are not free, and scripts are different.
A good rule of thumb is to put your style sheets in the head and your JavaScript at the very bottom of the body. Of course JS libraries give you some sort of "on DOM ready" to attach to. You can use this, and most devs do, but there are side effects:
IE occasionally barfs on the DOM-loaded hack. Rare, but it's happened to me.
Your page will be frozen until your scripts load if they are in the head. If you have too many scripts, that can make your page look slow and non-responsive.
If your JavaScript is all at the end of the page, you'll never need to worry if stuff is loaded or a DOM node is available. And the page will be rendered and styled while your JavaScript is loading and calculating.
Finally, keep your resources to an absolute minimum. If you have more than two scripts and two style sheets, your page is not as fast as it could be. Images too - make full use of image sprites. There should only be a handful of images unless you are dealing with thumbnails or something like that.
K-I-S-S is my dogma. When my code does not work, it starts usually to work when I kill non-intrinsic code.
Some good things are covered in replies such as mwilcox and prodigitalson.
No unnecessary pictures and no excessive script blocks. Actually, some people seems to have working-JS-code of over 500 000 lines, example with Gmail.
I have no idea how they do it but it hints to be critical about the replies here! Further replies could cover how to design massive JS code like of the size 100 000 lines, for the time being.
Exceptions
libraries and analytics scripts are an exeption and go to the beginning (if needed at all). Due to this kind of messy things, you may see why the term structure become confusing. But to craft some sort of structure, it would look something like:
CSS
Divs
scripts at the end

JavaScript-library-based Project Organization

I'm very new to the JavaScript library world. I have used JS by itself before to create a mini social network but this is the first time I use a JS library and I really don't know how to go about this.
I'm planning to use Google Closure and I'm really not sure how I should go about organizing the code. Should I put everything in one file since it's a web app and should have one screen? Should I separate the code to many chunks and put them in different files? Or should I put different dialogs (like settings) in a separate page and thus a separate file?
Like all programmers I'm a perfectionist so please help me out with this one, thanks.
If you're using Closure, you can use the closure compiler. I'd recommend multiple js files that are compiled into a single resource by the compiler. You'd reference that single js file in your html, so you wouldn't have to link to all of them.
Then, since you have multiple JS file, you can organize them in a logical way that will help you separate logic from UI from communications, etc. Also, if you're writing unit tests (JsUnit) it will be easier to write one test file per js file.
Depends...
What I do is add all my code in one file(librarys are always in different files) and then even though some of it wont be used, there will be no need to add multiple scripts to the page. If you have 20 files with script, it can be very confusing knowing which one to use.

Categories

Resources