I've spent a great deal of time creating and testing an application with quite a few functions. Now that I have configured everything and it works how I want, I would like to begin cleaning up the code so its not 400 lines of mush.
I have already created an external CSS file and would like to do something similar for the JS and possibly even the HTML (approx 100 lines of code of just HTML, ick).
Admittedly I am a novice programmer but I've picked up quite a bit of knowledge in the short time I've been doing this. What is the best way to separate out the functions into external files and then call them so that the whole application works as it does now?
For example (this is a web mapping application): I have functions for search, basemap gallery, legend, layers, init, infowindows, etc. Since the code is already written and I'll be creating multiple applications in the future, the goal would be to just have these js functions in files ready to be referenced by whatever application needs them.
Thanks.
To link an external javascript file, place a script tag with a src attribute pointing to your file.
<script src="legend.js"></script>
<script src="layers.js"></script>
<script src="init.js"></script>
Calling a function requires nothing special.
onclick="myFunction();"
Could you not just put all of those functions in one .js file and then call the file from within your web page?
<script src="../scripts/javascript.js"></script>
And then call on your functions as and when you need them?
The first thing you might consider doing do is to create a non-global "namespace" for your functions in a fashion such as the following:
window.MyApp = window.MyApp || {};
The above line can be at the top of every file; the first time it is invoked it creates a new namespace/object, subsequently it returns the one you previously created.
Then you can move your functions under MyApp in a manner such as the following:
MyApp.func1 = function() {...}
Google for creating Javascript namespaces, and possibly also the Javascript module pattern
Related
I am new to javaScript and am unsure how to go about creating a new js library and referencing this in another js file.
If I have a standalone file Utilities.js
var Utilities=
{
show: function(input)
{
alert(input);
}
};
Am I missing something as to how a library should be defined standalone?
My second question is how to use that is sub-sequent js files. What I did so far is:
<script type="text/javascript" src="resources/Utilities.js"></script>
In my index.html. Is this enough to reference it as:
Utilities.show("Hello");
In any other java script file?
I tested it in this fashion and got and error "Utilities is not defined"
NOTE: This is just an example and not my full and practical purpose.
Yes, including that Javascript file with that global variable declared is enough to call your methods this way Utilities.show("Hello"); from another Javascript file loaded after Utilities.js or inside a <script></script> section of your html.
But you can actually improve it a little, following the module pattern and exposing only the functions you really need to the global scope (you'll likely write some functions that the users of your library should not call directly, this allows you to do it in a clean way):
var Utilities=Utilities||(function () {
//Accessible only here
var privateArray=[];
//Cannot be called from outside this function
var privateFunction=function(){
}
//Return only what must be publicly accessible, in this
//case only the show() method
return {
show: function(input){
privateFunction();
alert(input);
}
}
})();
That (function () { /* Code */})();, defining a new scope for your code will also avoid name clashes with other global javascript object/functions.
It is OK to use object literals, but you can define libraries using other patterns (module, revealing module, constructors, etc).
I recommend these links to understand primitives, scopes, closures, object literals, etc.
http://bonsaiden.github.io/JavaScript-Garden/
http://jsbooks.revolunet.com/
To call the method inside index.html you need to add a tag.
<script>
Utilities.show("Hello");
</script>
But this approach it's not recommended. Instead of it, you can create a new JS file to run your library code.
<script type="text/javascript" src="resources/Utilities.js"></script>
<script type="text/javascript" src="resources/main.js"></script>
In main.js
Utilities.show("Hello");
Hope it helps.
Given the fact that you gave, within yout question, zero context of what you're trying to achieve, the best answer to your original question is that it depends.
If you just need a bunch of files and you're done (like in your example, Utilities.js and a few more) then you're ok with the way you're heading to.
But of course, you'll allways want to scale your front end and thus you should adhere to some architectural pattern. So, if you're building a client side (browser-side) application, then you should really implement your libraries using the module pattern, and begin your project from a good project example / scaffold.
On the other hand, if you're rendering the html on server (e.g. you're using PHP to render the final html file that will be sent to browser) and you just need some thin functionality in the browser, the way you begun can be okay if you're careful. Also, you can still implement the module pattern here too, although I strongly suggest that you should make use of namespacing to have a clear separation of concerns.
In browser based javascript you can't just call functions from different files yet. In Es6 there are ways. But not yet. Which mean just because you have some variable or function etc then you cant reference it automatically in another file.
Unless both files are loaded into one html and are loaded in order.
Alternatively you could run task runner like grunt and 'merge' them upon each build.
Javascript doesnt have special concept of library, in es6 it's a little different, everything is an object.
What you are doing is just creating an object. and yes it will work.
I have a log.js file(it contains log function along with some properties) for debugging purpose.
I have two other js file which are the controlling various behavior of the web application.
Now I need to include the log function considering not to repeat the debug function in both the js file and just calling the file name.
How do I do it?
The idea is to make my code clean and separate them in other files to limit the size of a single js file.
Include all .js-files in the html page. Include log.js first.
Call the functions all you want.
All functions in all files are included in the source and are "written on the page", any functions can be accessed from anywhere within the HTML as they all become essentially one document. Make sure you do not have duplicate functions as this could cause an issue
I've seen quite a few questions regarding loading a .js file into an HTML file, and I know how to do that. However, say I have the file "classlist.js." How can I go about using the classes defined in that javascript file in another javascript file? I keep seeing answers that suggest using the
<script type="text/javascript" src="filepath"></script>
syntax. When used in a .js file, though, it throws a syntax error on the "<" so I assume this code is invalid.
So, how would one utilize a function in a .js file that was defined in a separate .js file... that works, and is efficient (If there is one)?
EDIT:
I'm going to clarify some thing for the future, since I'm still fairly new to Javascript, and it looks like there were a number of other factors I didn't even know came into play.
I had two .js files, one of which declared classes that were extensions of classes in the other file. I wanted to use the extended classes in a webpage, and I thought I had to load the originial classes into the second .js file, THEN load that .js file into the HTML file. I wasn't programming completely outside of HTML.
Sorry for any misunderstanding, hopefully this thread is helpful to somebody else in the future.
Assuming you are talking about javascript in a web browser, all js files are loading in an html file, typically index.html. You need to use the script tag to load the javascript in the proper order in that html file, not in the javascript file. So if file B requires the things in file A, you need to load file A first, meaning put the script tag that loads file A before the script tag that loads file B.
Two answers:
Non Browser
If you're using JavaScript in a non-browser environment (NodeJS, RingoJS, SilkJS, Rhino, or any of a bunch of others), the answer depends on the environment — but many of these use the CommonJS require mechanism. E.g.:
// Get access to public symbols in foo.js
var foo = require("foo.js");
// Use the `bar` function exported by foo.js
foo.bar();
Browser
If you're using JavaScript in a browser, you put script tags like the one you quoted in the HTML, in the order in which they should be processed (so, scripts relying on things defined in other scripts should be included after the scripts they rely on).
If you want to maximize efficiency in terms of page load time, combine the scripts together on the server (probably also minifying/compressing/packing them) and use just the one script tag.
The answers posted above should do the trick however since you mentioned doing it efficiently you can consider taking a look at javascript module based loaders like require js( http://requirejs.org/ ) based on AMD
You have to put the reference to classlist.js in your HTML file (not your Javascript file), before any other SCRIPT element which requires it. For example, within the 'head' element:
<html>
<head>
<script src="testclass.js"></script>
<script src="file_using_testclass.js"></script>
<script>
var tc = new TestClass();
</script>
</head>
I have created a string builder JavaScript object and I'm using it with many different .js files in my project.
Can I create this class in a separate .js file and call it from all the other scripts that instansiate it, just like a C# class file?
Is this possible, or do I continue copying and pasting it into the bottom of every .js file that uses it?
Yes, this should not be a problem. Just include the .js files in the correct order in your html pages.
If you include the file in your main HTML page with your other js, you can then use the "class" as you wish:
<script src="js1.js" type="text/javascript"></script>
<script src="js2.js" type="text/javascript"></script>
In the above example, you can now instantiate a new instance of an object from js1.js with the code in js2.js. To do this with pure javascript, you would have to add the script tag to the DOM, or use AJAX to fetch the script file and eval() it.
// Create a <script> element
var scriptEl = document.createElement("script");
scriptEl.src = "js2.js";
scriptEl.type = "text/javascript";
// Append it to the <head>
document.getElementsByTagName("head")[0].appendChild(scriptEl);
To be perfectly correct, it's not the order of inclusion that matter, but rather the order of executing code. In most cases, Andy's and Segfault's instructions are just fine, but sometimes including the class file before its consumers isn't sufficient. For example, if you use ExtJS and you happen to define your class inside an onReady handler like this:
Ext.onReady(function() {
myClass = ...
}.bind(this));
then it won't get executed by the time your second src file is included into the page and executed.
I know, the example is a bit far-fetched :) but just make sure that your code is executed in the right order, not just included in the right order.
I came across this question and I wanted to add something (which probably wasn't there a few years ago).
Even thought you can add every single script to your "index.html" it's not a very beautiful practice (imho). Especially if you consider that you may want to write a extension (~ framework). You don't want to annoy the user with a bunch of script tags he has to add to his code. What you want is a single line like this:
<script src="yourFramework" (...) />
However, with the use of RequireJS you are able to achieve this. You've the freedom to separate your code and "your user" still don't have to add a novel to his "script section".
There are essentially 2 places to define JavaScript functions in Grails, directly in a element on the GSP, and within a separate javascript source file under /web-app/js (for example, application.js). We have defined a commonly reused javascript function within application.js, but we also need to be able to generate parts of the function dynamically using groovy code. Unfortunately, ${some groovy code} does not appear to be processed within separate javascript source files.
Is the only way to do this by defining the javascript function within a script tag on a GSP page, or is there a more general solution? Obviously we could define the javascript function in a script tag within a template GSP file which would be reused, but there is a lot of push to keep our javascript functions defined all together in one place (i.e. the external javascript source file). This has performance benefits as well (the javascript source files are usually just downloaded once by each client's browser, instead of reloading the same javascript functions within the source of every html page they visit). I have toyed around with the idea of breaking the function up into static and dynamic pieces, putting the static ones in the external source and putting the dynamic ones in the template GSP, then gluing them together, but this seems like an unnecessary hack.
Any ideas?
(edit: It may sound like the idea of dynamically generating parts of a JavaScript function, which is then downloaded once and used over and over again by the client, would be a bad idea. However, the piece which is "dynamic" only changes perhaps once a week or month, and then only very slightly. Mostly we just want this piece generated off the database, even if only once, instead of hard coded.)
An easy solution to keep your JavaScript unobtrusive is to create a JavaScriptController and map its actions "/js/*" by adding this to your UrlMappings.groovy file:
"/js/$action"{
controller = "javascript"
}
then just create an action for each dynamic JS file you want, include in in your layout <HEAD>, and presto, you've got a JS file that you can insert Grails snippets into! :)
Note: I've found that there's currently a bug in Grails that doesn't map file extensions to content-types properly, so you'll need to include <%# page contentType="text/javascript; UTF-8" %> at the top of your view files.
This is a great solution. I would like to offer a suggestion to use somthing other then a mapping of "/js/$action" because this is no longer going to allow you to access you javascript files in /web-app/js/. All your javascript files would have to be moved to a the directory your controller would point to.
I would use something like
"/dynjs/$action"
This way you still can point to files in the /web-app/js/ files with out conflict and enjoy the benifits of gsp tags in javascript files
Please correct me if I'm wrong.
Or this... have a tag/service/dynamic method that lets tags write out their JS+CSS+whatever else, to a "cache" which is used to build the JS+CSS resources by a different controller.
Full concept here: [http://www.anyware.co.uk/2005/2009/01/19/an-idea-to-give-grails-tags-esp/][1]
If you want to use models created by the controller (that rendered HTML page which reference the Javascript in which you intend to use groovy code) in the Javascript code, then you can use this technique:
This technique does not need to change URL mappings and does not require you to create extra controller.
In your view GSP add javascript as follows:
<script type="text/javascript">
<g:render template="/javascript/yourJavascriptFile"/>
</script>
In views folder create a "javascript" folder. And create a file named:
_yourJavascriptFile.gsp
You can not only use all the GSP code in your _yourJavascriptFile.gsp file, but you can also use all the models created in your controller (that is rendering the view).
NOTE: There is nothing special about javascript folder. You can name it anything you want OR use an existing view folder. This is just a matter of organizing and identifying your HTML spitting GSP from Javascript spitting GSPs. Alternatively, you can use some naming conventions like: _something.js.gsp etc.
Name your scripts like this
/wherever/the/js/files/are/thescript.js.gsp
The gsp code inside will be rendered correctly by grails. This works, but I have no idea if it's considered a Good Idea or not.
There is another way - pass in the generated code into a function that expects closures. Those closures is generated by the program of course. The generated code is of course inlined/script-tagged in the gsp page.
it may or may not work depending on the nature of the code being generated. But i suspect it will work, and if it doesnt, minor tweaking to the coding style of your javascript will definitely make it work. Though, if these 'generated' code doesnt change much, this quite overkill imo.