I'm trying to load a single javascript in pieces by calling the javascript from external separate files, and was wondering the best way to go about doing this. Specifically, this is a just a basic google maps page, and I want to organize the code a little better. I'm hoping to split the marker variables up into groups and store those groups of variables in separate files, then call those files within the main javascript header of the page. I want to restrict this code to just html and javascript to maintan its simplicity for the purpose of future updates by individuals less than knowledgeable in this area. I don't do a whole lot of coding with JavaScript so, if there already is a built-in function for this, that would be great. This is purely aesthetic, just to make the code a little cleaner. Any help or suggestions would be appreciated. Thanks.
If I understand you right, you don't want to call one JavaScript files from several another JavaScript files. You want just save some groups of variables. Well, you can save it - with a server-side database or, may be, with http://www.w3.org/TR/webstorage/ or http://www.w3.org/TR/IndexedDB/
You can add references to external files:
<html>
<head>
<script type="text/javascript" src="colorGradient.js"></script>
<script type="text/javascript" src="xpath.js"></script>
<script type="text/javascript" src="kml2.js"></script>
<style type="text/css"> ... </script>
</head>
<body>
....
</body>
</html>
You can try a "feature loading" and/or "on-demand javascript loading" framework. Since you're trying to use Google maps, I would recommend you use the Google Loader API which works very closely to what you're seeking.
for example: With a simply JS you can do the following....
<script type="text/javascript">
google.load("search", "1");
google.load("jquery", "1.4.2");
google.load("jqueryui", "1.7.2");
</script>
... and it will load the multiple files.
Splitting up you code for your development is a good idea. There for, there are a lot of frameworks to help you organize your code with the help of MVC and psudo MVC models.
Try:
http://maccman.github.com/spine/
or
http://documentcloud.github.com/backbone/
But what prevents you from having everything in one file on the production environment?
Its easier on the server requests. And you want to integrate this in your build process anyway...
But if you insist in on adding them to the DOM you can do this of course:
document.write(unescape('%3Cscript src="yourfile.js"%3E%3C/script%3E'))
this will add
<script src="yourfile.js"></script>
to your dom
If I understand your question correctly, you would like to split up a single script into multiple .js files. As far as I know, this should work fine as long as you include a tag to load each file. You may need to load the files in order (i.e. don't include a file that calls a function that has not been difeined yet).
However, be aware that splitting up your script will result in more calls to the server, which will slow down page load. In most cases, just including a few scripts won't even make a noticible difference in load time.
Related
Can I write it like this? Won't I have issues in terms of how fast my website loads?
for index.html:
<html>
<body>
<script src="index.js"></script>
</body>
</html>
for about.html:
<html>
<body>
<script src="about.js"></script>
</body>
</html>
for contact.html:
<html>
<body>
<script src="contact.js"></script>
</body>
</html>
I just want to clear things up. Thanks in advance!
You should extract out common features among all the javascript code you run on different pages.
Imagine index.js has a function to create a list. And about.js has the same function. When it comes to updating that function you will want to change it in one place. Not the five pages you have.
As for speed if every page has a link for list.js file, it will only need to be downloaded by the browser once. It's code will be cached and used in all the other pages requested.
Yes you can use it like this way, your website load faster. But if you include all the JS to all the files, it'll load slower because loading time is increased coz all the three files load for all the three pages.
Or a different approach.
Try to convert all the three file into only 1 (This way you'll reduce the repetitive function)
Then include this file to each file.
By storing the file to cache memory, file only download (load) once then it'll be used from the cache memory. This way your speed will be increased.
Refer to the following link:
https://www.html5rocks.com/en/tutorials/appcache/beginner/
Try to research as much as possible. You'll get your solutions.
Tick right (✓) if my answer is helpful for you.
The pages load separately so having a script in another page does not affect how fast the current one loads.
In my opinion, if you are very concerned about the speed it is more important to ensure that you are only loading the scripts that you need in the current page.
The right approach is to split your code into multiple functions as appropriate.
To address loading performance, use a minifier which will minify and bundle all your code (include JavaScript, CSS and HTML). You won't be able to outperform an actual minifier anyway.
Depending on the technology you are using, minification can be a step during your build/deployment procedure, or a plugin for your CMS which will minify and cache your files as they are being accessed.
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>
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.
Ok, stupid question and I don't think it's possible but, I have this markup at the top of my .aspx page...
<%--Third Party Libraries, Plugins, Extensions --%>
<script src="Libraries/Raphael/Raphael.js" type="text/javascript"></script>
<script src="AutoComplete/jquery.autocomplete.js" type="text/javascript"></script>
<script src="Libraries/jQuery/1.4.2/jquery.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.core.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.widget.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.mouse.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.draggable.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.droppable.js" type="text/javascript"></script>
Wouldn't it be nice if I could replace that with this...
<%--Third Party Libraries, Plugins, Extensions --%>
<script src="Libraries/Raphael/Raphael.js" type="text/javascript"></script>
<script src="AutoComplete/jquery.autocomplete.js" type="text/javascript"></script>
<script src="Libraries/jQuery/1.4.2/jquery.js" type="text/javascript"></script>
<script src="Libraries/jQuery/UI/1.8.4/jquery.ui.*.js" type="text/javascript"></script>
ie use the * as wildcard.
Obviously as this is JS I could just throw all those scripts into one big script and load that but I don't really fancy doing that.
Anyone else have a technique for tidying up masses of script refs? Or do we just live with it?
As far as I know this is not possible, simply because, the browser would need to know exactly what files to request.
The browser would essentially have to brute force your server with requests hoping to get lucky.
I'd suggest using Google's closure compiler to merge all similar, if not all, javascript files into a single file. It will be slightly large, but would cut down on http request.
With some profiling you could find a balance between which files are needed most commonly and speed.
UPDATE (from comments)
I'm generally reluctant to offer adding a new javascript library to solve the issue of too many javascript libraries :) Plus this just seemed like the more straight forward solution. Current we use the Google closure API to compress and merge all our javascript and CSS and build time with ANT. Works a charm. This can also be done to some extent direct with apache2 virtual host/htaccess (see html5boilerplate.com) for examples and limitations
Nope, not in the way you're thinking of. You could do something that's similar if you're using JavaScript loaders (e.g. RequireJS or LabJS), since you can then condense each file into an array and loop through them, or, if you're feeling ambitious cook up some protocol between the front and back ends to support this.
Nonetheless, this is not recommended as it's not easy to maintain. If your problem with combining the files into a single one is with the effort, then JS minifiers (e.g. UglifyJS or Closure Compiler) may solve your problem.
Actually, as somebody else may have mentioned, you could add your own script file in there and do something like add the paths to an array, loop through it calling getScript for each item.
$.getScript('ajax/test.js', function() {
alert('Load was performed.');
});
ie use the * as wildcard.
No. Well, not unless you want to configure your server to pass a URL which includes a * character through a script that resolves it and bundles up all the JS on the fly.
Obviously as this is JS I could just throw all those scripts into one big script and load that but I don't really fancy doing that.
It's a good solution. Generally you would want to do this as part of a build script for the site, and throw in a call to a minifier at the same time.
I would omit type="text/javascript"
The "type" attribute is required in HTML 4, but optional in HTML5.
But I still think that merging src is impossible (as of HTML5 and CSS3)
You could just copy the contents of all the jquery.ui.* files into one file. As an added bonus, your pages would load slightly faster.
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.