Splitting code into different Javascript files - javascript

I am working on a Javascript/HTML5 canvas based game and so far my JS code is 1200+ lines long.
I am using lots of Objects and lots of different function as well so a question came to my mind.
Is there any possible way to have separate objects in separate JS files and a main file where I would refer to those separated objects in their own JS files? I just want to keep my code simple cause it is starting to look a little messy.
Thank you

Like akluth said, you can use external libraries to "load" your external Javascript files.
If you don't wish to use any of these then it's the gool'ol fashioned JS way: You include all your external files like so:
<script type="text/javascript" src="external/file.js"></script>

You can use requireJS for this - it allows you to seperate your code into AMD modules which can be easily used accross your project.
To have optimized and minified code in your production environment you can use r.js, the requireJS optimizer which allows you to concat all your modules into one minified and uglified file.

The simple answer is yes. You can place each object and its properties and methods in its own file loading each file as Jarrod suggests.
<script type="text/javascript" src="external/main.js"></script>
<script type="text/javascript" src="external/obj1.js"></script>
<script type="text/javascript" src="external/obj2.js"></script>
where 'external' is a directory in the same folder as your HTML file.

Related

How can I access and use multiple javascript libraries?

I am new to javascript and programming in general. I have been working on a web app that solves simple algebraic equations. I am using two libraries, algebra.js and katex.js. How do I use both libraries in my script? I would like to keep this as a client-side application.
I have looked at node.js but my understanding is that node is for server-side development. I have looked at RequireJS but that doesn't seem to handle directories well. Recently I found Enderjs which seems to use npm and allow for client-side development and still make use of require().
What should I use to make a web app like this? Please let me know if there is anymore information that is needed.
The most basic way to do this is to include multiple script tags at the top of your html file. So:
<head>
<script src="path/to/library1.js"></script>
<script src="path/to/library2.js"></script>
<script src="path/to/my/javascript.js"></script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
</body>
This will load more than one onto the page. The order might matter - be wary of which dependencies your chosen libraries have. For example, some will depend on jQuery, so you should load jQuery first then those that depend on it. Order is top down.
In my example, if we pretend library2 depends on library1, then the example would work. However if library1 depended on library2, it would not.
The simplest way is to include the script tags directly in your html file like so (this assumes that you have the algebra.js file in the same folder as your html file):
<script src="algebra.js"></script>
If you are loading the library from the internet you have to use the full web path in the src attribute, for example loading the jQuery library from a cdn (content distribution network):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

ClojureScript-Lib and my ClojureScript on same page

Let's assume I have a small web-application and want to use a third-party library that comes with an already compiled version of a ClojureScript.
As a user of that library I have to include that generated Javascript file in my HTML page.
<script src="/javascript/gen/lib.js" type="text/javascript">
So far so good. Everything works fine.
But since my web-application needs some frontend-magic, I wanted to include some ClojureScript of my own. So I wrote a couple of lines, compiled it to Javascript and added another line in the HTML head:
<script src="/javascript/gen/lib.js" type="text/javascript">
<script src="/javascript/gen/my-stuff.js" type="text/javascript">
This is, where it gets ugly. I get this error in the javascript console:
Error: Namespace "goog.debug.Error" already declared.
After googling that error, I get multiple pages, that state, that I can not use multiple Google Closure Compiled things on one page. See SO: Multiple ClojureScript files on same page
So, how do I tackle that situation? On one hand I have an already Google Closure compiled lib and on the other hand my ClojureScript stuff. How do I get one (or two) compiled Javascript files out of this?
Would it be easier, if that third-party lib would provide a non-compiled ClojureScript version?
Yes, it would be easier if the third-party library would provide a non-compiled ClojureScript version. Then you would require it and use it from your code and compile everything together. The ClojureScript compiler with require each dependency once (even the shared dependencies) and the Google Closure compiler would do its optimization pass over all the code.
Try to find the library in Clojars or package it as a jar to consume it from your existing ClojureScript setup. (If the library is open source, give us a link and we'll help you out)

uglyfy - I've combined all the js files. Now what?

I started a small web/html project, in which I will have at least a few js files, including dependencies and stuff.
Just because I like it clean, I'd like to minify all those files into one. That's pretty easy with uglifyjs and grunt, problem solved.
But there's something else: in my "source" (uncompiled) html file, I have a bunch of <script> tags. Something like this:
<script src="js/dependency1.js"/>
<script src="js/dependency2.js"/>
<script src="js/mystuff.js"/>
But as I said above, after the build I end up with one big file, allTheStuff.js. I wish I could automatically modify my HTML to:
<script src="js/allMyStuff.js"/>
Is there a way I can do that automatically? Any tool to recommend?
And same question for CSS.
Try grunt-usemin for this. It will handle both javascript and CSS.
From the GitHub page for the project:
Replaces references to non-optimized scripts or stylesheets into a set
of HTML files (or any templates/views).
When it works, it's a really nice tool to simplify the exact problem you describe. The downside is that it's a little clunky to use as you juggle the HTML tags usemin needs and the grunt configuration.
But, clunky config issues aside, I've used it and it's very nice to automate the copy, concat, and uglify steps and to modify the HTML to use the results of those tasks.
Related: grunt-include-source offers automation to inject a list of files into your HTML. If you decided you wanted to handle things yourself rather than turn it all over to usemin, this tool is a handy item to automate updating the HTML as you build a custom build process based upon your needs.

How to combine multiple scripts into one script in JSP?

Here are my scripts
<script type="text/javascript" src="../js/btgAportion.js"></script>
<script type="text/javascript" src="../js/tab.js"></script>
script type="text/javascript" src="../js/jquery_calc.js"></script>
<script type="text/javascript" src="../js/jquery_onload.js"></script>
<script src="../js/jquery-latest.js"></script>
<script src="../js/collapsible.js"></script>
They all are in common js folder
I want to combine all these scripts into one script to reduce HTTP requests
There are a number of approaches. Edit, if you're going to downvote me, let me at least say, this tool of mine is a java tool for aggregating javascript files together for exactly the purpose you want:
http://damonsmith.github.io/js-class-loader/
Otherwise, if you want to roll your own JSP based solution, you can create a scripts.jsp which reads each one and just concatenates them all together into the output, then use that scripts.jsp inside your HTML script tag. It's probably easier for small sites than my over-engineered tooling.
You can use https://github.com/dfsq/compressJS.sh shell script to compress multiple JS files to one.
From official ReadMe:
Very simple bash script which compresses javascript files with Google
Closure Compiler and then make a single file of them. Reduce file
sizes and save bandwidth with just one simple command.
Reduce number of HTTP round-trips by combining multiple JavaScript resources into one.
https://developers.google.com/speed/pagespeed/service/CombineJavaScript
compress javascripts by using : http://jscompress.com/

Keeping my jQuery code away from the html files

I am learning jQuery and have a created several plug ins.
Unfortunately due to my company's coding practices they want all javascript code to be extract out to js files. This for me poses two challenges:
Can i extract the actual $(document).ready(..) call to a js file? So far with my limited knowledge I have not figured if this at all possible. If not, I welcome any suggestions to make this cleaner and more acceptable way to include this code.
There are too many javascript includes for each asp.net page header since I may be using several plugins. Is there a way to reduce the potential costly server trips that I would need to make each time I need these files?
Any suggestions, corrections are greatly appreciated
thanks
1. Absolutely.
Just add a script reference to your html like this:
<script type='text/javascript' src='js/yourfile.js'></script>
Then just start your .js file with
jQuery(function() {
foo;
...
bar;
});
or any other shortcut ways of starting the jQuery code block.
2. You should run your scripts through something like Minify before sending them off to the user. This will combine the files and pack them in nicely, so that they take up less space.
Using $(document).ready () in an external javascript file is fine - it will work exactly the same :) In fact - not only will it work, but it is good practice as it helps to seperate the content (HTML) from the behaviour (Javascript).
In response to your section question - you can combine all of your plugins into a single javascript file and link to that one inside the <head>. You could also try minifying the scripts, although this is normally a bit overkill until the site goes live.
When I use jQuery, I normally use this kind of structure:
<html>
<head>
<!-- html tags such as title, link, meta etc -->
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/plugin.js"></script>
<!-- more plugins included if required -->
</head>
<body>
<!-- html here -->
<!-- script is the last thing before the ending body tag (increases performance) -->
<script type="text/javascript" src="/path/to/your_jQuery_code.js"></script>
</body>
</html>
I think worrying about server trips for javascript includes is premature optimization. Do you have any evidence that these pages are loading slowly? The browser should be caching the javascript files.
If you do have evidence that this is a problem, you could
-combine the jquery code and any plugins into one file
-write an .net content handler to do this for you (probably overkill)
Then you can add a custom js file per page to handle page specific properties.
You can most definitely put your document.ready and all other JavaScript code in an external file.
Typically I have 2 calls - one for jQuery itself, and one minified global.js file that combines and minifies all of my individual files.
Personally, I like to use front end blender for this, but there are many other options available as well.
there's nothing wrong w/putting the document.ready call in an external file. in fact, it's what i do to separate my js from my html. if you're concerned about certain functions running on certain pages, you may sift through them with a
var path = window.location.pathname;
if (path == "/yourdir/yourpage.html") {
//do something for this page only
}
or you can just include certain files only on certain pages.

Categories

Resources