Calling a JavaScript object class that's in a separate .js file - javascript

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".

Related

Managing page specific Javascript: 1 big file with conditionals or multiple files

In my project I have a load of functions that are used on every page, so I have put these in a single javascript file common.js and have included it in my footer template. My questions is, what is the best way to handle page-specific javscript?
For example, on one of my pages I have a google map. If my map js code is run on a page where I don't have an element with id map_canvas, I get an error.
Method 1: I could write some PHP which echos an additional script tag requesting map.js if and only if I'm on a map page.
Method 2: I could give the <body> of my map page an id of "map_page", then I could write a conditional clause in common.js along the lines of:
if (#map_page exists){
put contents of map.js here
}
The problem with method 1 is that it increases the number of requests to the server.
The problem with method 2 is that it bloats my common javascript file.
Please can somebody explain, which, if any would be the preferred method to do this, or if neither are suitable, what I should do instead?
I have approximately 10 page-specific javascript files to deal with.
Thanks
I would say that simpler is better. On every page, just add a script tag calling map.js. Or, in your common.js, you don't need to paste all of map.js's code. You can just create a new script tag with the js and call map.js like that. I would not recommend the php method. The easiest and simplest, therefore the least likely to be buggy method, is just to add another script tag to the pages that need it. Or if that is not an option, common.js could include this:
if(need map.js){
var mapjs=document.createElement("script");
mapjs.type="text/javascript";
mapjs.src="map.js";
document.body.appendChild(mapjs);
}

How do you import multiple javascript files in HTML index file without the bloat?

Is there anyway of importing multiple javascript files in HTML without having to specify each file?
<script src="js/toolkit/Toolkit.js"></script>
<script src="js/toolkit/Viewable.js"></script>
<script src="js/toolkit/Overlay.js"></script>
ie. can I specify something like js/toolkit/* ?
I have 50+ javascript files that i have to import, and to specify each file seems very time consuming.
Including a JavaScript file in another JavaScript file is common in web development.
Because many times we include the JavaScript file at run time on the behalf of some conditions.
So, we can achieve this using JavaScript as well as using jQuery.
Method 1: Use JavaScript to include another JavaScript file
Add the following function in your web page.
function loadScript(url)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
}
just call the below loadScript function, where you want to include the js file.
loadScript('/js/jquery-1.7.min.js');
Method 2: Use jQuery to include another JavaScript file.
Add jQuery File in your webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
Just call the getScript function functions.
jQuery(document).ready(function(){
$.getScript('/js/jquery-1.7.min.js');
});
How to include a JavaScript file in another JavaScript File
There's a way:
You can create a javascript function that takes the path as a parameter and creates these HTML lines:
<script src="js/toolkit/Toolkit.js"></script>
<script src="js/toolkit/Viewable.js"></script>
<script src="js/toolkit/Overlay.js"></script>
And you'll just have to call this:
loadLib("toolkit/Toolkit");
loadLib("toolkit/Viewable");
loadLib("toolkit/Overlay");
But this is not recommended because the load time will be increased due to the number of HTTP requests.
You should better use something in the server side to put everything in the same file.
No you can't do it. And by the way this is not good idea to load all 50 separate files. Consider compressing them in one single script to improve performance and decrease page load time.
You can setup grunt to watch the folder of the scripts and concat/minify them into a single file, then you just have to include that in your HTML file.
You will need to specify each file for the browser to know what to retrieve, but depending on the IDE you are using, there may be shortcuts for doing this, (Visual Studios allows you to drag and drop script files into the html to add references).
During development, you want to do just as your doing by keeping the files separate for troubleshooting, but in production, as others have commented, its very good practice to minify your code and combine them into one file. That makes it only one call, and can reduce your overhead significantly.
I recommend you to use JSCompress. It will compress all your javascript code into one single javascript file.
import "./angular.min.js"
import "./jquery-3.6.0.min.js"
import "./app.js"
<script type="module" src="js/importJS.js"></script>

Access function defined in separate .js file from a .js file

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>

Create and Call External JS files

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

Executing groovy statements in JavaScript sources in Grails

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.

Categories