How to import/include source files in JavaScript? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to include js file in another js file?
Suppose I have a few JavaScript source files: a.js, a1.js, and a2.js. Functions of a.js invoke functions from a1.js and a2.js.
Now I have to declare all these files in my HTML page. I would like to declare only a.js in the HTML and "import/include" a1.js, and a2.js in the a.js source file.
Does it make sense? Can I do that in JavaScript?

You can't specify imports in vanilla javascript.
So your solutions (excluding heavy server side frameworks) are :
simply do the imports
concatenate your js files (and minify them in the same move, for exemple using the closure compiler)
use a module itool like require.js
As long as you're not experienced, and if your number of files is low (less than 15), I recommend to simply choose the first or second solution. Using a module loader may have side effects you don't want to debug when beginning to learn javascript.

You can import:
<script type="text/javascript"src="a1.js"></script>
<script type="text/javascript"src="a2.js"></script>
<script type="text/javascript"src="a3.js"></script>
if you want to do it directly from the JS, you may use Ajax, this post explains how to:
include-javascript-file-inside-javascript-file

You can bundle JavaScript (and also CSS) files together using certain tools to reduce the number of files you must include. This also increases page load performance.
These tools combine multiple JavaScript files into a single JavaScript file (optionally minifying the files as well), and multiple CSS files into a single CSS file. This results in fewer HTTP connections from the browser to the server, so there are fewer things to be fetched serially.
ASP.Net MVC 4 has built-in support for this:
http://theshravan.net/bundling-and-minification-support-in-asp-net-mvc-4/
There are a number of solutions for other environments as well such as Juicer.
If you cannot bundle all resources (perhaps some come from a CDN while others are served locally), you can use a load manager such as require.js.

Related

Web Page Performance - CSS and JavaScript in Separate Files? [duplicate]

This question already has answers here:
Comparison of loading CSS inline, embedded and from external files
(10 answers)
Closed 6 years ago.
Looking at the Google HTML/CSS Style Guide, I don't see anything specific. It seems like putting the CSS and JavaScript in the HTML file would perform better than loading external files.
For production Websites, should I include everything in 1 file, or no?
Usually when you develop, you split up your code in your project tree. So you have a large amount of js, and maybe css / sass / less files.. which represents smaller components for your project.
When you are going to launch your project to production, you usually have build program which concatenates all the files into a single bundle and this bundle is also minified, for faster loading like bootstrap.min.js for a example.
Take a look (google) for some production ready packer like:
brunch
webpack
It depends on your preference . but in most cases you would like to write code in separate files because when you work on big projects it can start to get confusing when you have css ,js and html in the same file .
plus the difference it will make is minimal to none.

Does creating javascript dll have any advantages over adding it directly using script tag?

I am working on project with larger javascript files.I can add these javascripts in one of the two ways.
1) create a separate class library project and have the javascript files there as embedded resource.Include a reference of the dll into the web project and then include those using scriptmanager as webresource.
2)Have these files in a separate folder and then simply add these files using the script tag and there path.
I am not going to paste the javascripts in my page within the script tag cause they would mess my pages mark up.
So I would like to know which one is better of the above 2 ways.In either of the 2 ways everytime i load the web page i see GET request for the js files.If i create a javascript dll will the browser cache it?
You can't create "javaScript dll". JavaScript is a client-side stuff, dll is server-side. No matter in which project your javaScripts are, it will still be sent to the client and executed there. So it makes no sense to put JS files to another project (especially as resources)
We usually want to minify and bundle the JS files, so the client will do less requests to the server and also to reduce the amount of data to transfer.
For minifying the JS files I would recommend to use Web Essentials extension to VS. It is very handy and can make web programming easier.
Minification will remove all unnecessary characters from the JS file and it will also reduce the length of the identifiers (like method names and variable names).
You can learn about bundling here. It is useful when there are more JS files to load to load all of them at once.

One big javascript file or multiple smaller files? [duplicate]

This question already has answers here:
Put javascript in one .js file or break it out into multiple .js files?
(11 answers)
Should I copy all my JavaScript sources into one single file?
(3 answers)
Closed 9 years ago.
Ok, so I have a reasonable size project, where I'm using jquery backbone and a couple of other javascript libraries. I was wondering if I should have one file for my javascript libraries and another for my custom code. Or a bunch of separate javascript files.
It is generally a good idea to have fewer HTTP requests. So you should reduce the number of files as much as is reasonable.
My personal preference is to have three "groups" of JavaScript files:
Core file. Contains functions that are used almost everywhere and other useful page initialisation things.
Module files. Contains code that is used in several places, but not everywhere. Can be dropped in to provide additional functionality. For instance, if you have a script to handle date inputs, you could include it as a module file and add it to pages that have date inputs.
Page-specific files. These files contain code that is only used in one place. The only reason they're added as separate files than as part of the page itself is for cache reasons.
One big file. You should minify the code when it goes to production and compress it if its large. You want to make as few requests to the server as possible to improve page performance
It's best to separate it out, but not get overzealous. That way you can reuse your library code later. Also, everyone likes working with separate files more because it keeps things more organized.
That said, it's also best to give the user one compressed file so that everything can be cached easily, and this also reduces the number of page requests. Rails 3 does this automatically in the asset pipeline, for example. You can write a script to run your favorite compressor. But you shouldn't sacrifice code readability for this -- you can have your cake and eat it too!
One big file or two files: one small and one big.
To be clear, during the development it's good have separate files – maybe using something like requireJS. But when you deploy it, it's good compress everything in one file, in order to reduce the HTTP latency and requests.
I mentioned two files. In some cases, it could be good having one small file, that takes care of the "bootstrap" operations, meanwhile the "big file" – especially if it's really big – is downloaded.
This is useful especially for the first access, because users doesn't have your files cached yet.
As a rule, I go with as few as possible simply to reduce the number of requests made to the server.
As suggested it is nice to work with smaller files, but for production code, your build process should include optimization. Part of that optimization should be minimizing the file sizes and network traffic optimzation, by combining into a single js file to reduce calls made by the browser.
Depends on the size of your application. But typically always better to group your javascript files appropriately for better maintainability and re-usability.
You could use a JS module loader like RequireJS to load your JavaScript. At least the files will be organized. You can enhance server performance by making sure these files can be cached on the user's browsers so that they only download them once.

how to create makefile in javascript? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Make File for Javascript
Actually i am writing some javascript for testing purpose.
i want to use multiple javascripts in which functions are defined.
Is there any way to achieve this ?
I think Make file is the way.
But i don't know that also.
I want to generate make file.
Can any body suggest me how is to be done?
Creating makefile is an interesting solution, but you can also use require.js library to set the sequense of loaded scripts.
If you looking to combine multiple scripts as one. You can the use build script Boilerplate.
Why to use it? Its not only about scripts.
Combines and minifies javascript (via yui compressor)
Inlines stylesheets specified using #import in your CSS
Combines and minifies CSS
Optimizes JPGs and PNGs (with jpegtran & optipng)
Removes development only code (any remaining console.log files, profiling, test suite)
Basic to aggressive html minification (via htmlcompressor)
Autogenerates a cache manifest file (and links from the html tag) when you enable a property in the project config file.
Revises the file names of your assets so that you can use heavy caching (1 year expires).
Upgrades the .htaccess to use heavier caching
Updates your HTML to reference these new hyper-optimized CSS + JS files
Updates your HTML to use the minified jQuery instead of the development version
Remove unneeded references from HTML (like a root folder favicon)
Runs your JavaScript through a code quality tool (optional)
If you have several separate files and you want to append them all it into one file before, f.i. using it one your website, then any script or tool is good: Make, Rake, Cake, or your own, in your language of choice. If it goes to the web, it should be also compressed. Now how to do it, is beyond scope of this question, there are loads of articles on the web about all those topics. You are encouraged to come back when (if) you hit some more detailed problem.

javascript "include" strategies [duplicate]

This question already has answers here:
Closed 14 years ago.
Duplicate of: Use javascript to inject script references as needed?
Javascript doesn't have any directive to "include" or "import" another js file.
This means that if script1.js uses functions/objects defined in script2.js, then every html page that includes script1.js must include script2.js before it.
This shouldn't be a big problem if you only have 2 js files in like 10 html pages. I mean, it's manageable then!
But say suddenly you change script1.js and improve it by using functions/objects defined in a new file, script3.js
The problem is, you can't just tell script1.js to include script3.js, instead, you have to remember every html file that included script1.js and update it to include script3.js as well!
This seems like rather stupid way of organizing code.
Are there recommended strategies or practices to deal with this issue?
Would it be acceptable to have a gigantic js file that holds all the functionality that you use across the website?
Use dynamic includes:
Use javascript to inject script references as needed?
Scriptaculous (and probably other frameworks) handle this by writing script tags for the included files to the document when they are loaded. Below is the relevant bit from the scriptaculous.js file that allows loading the other files in the framework.
var Scriptaculous = {
Version: '1.8.2',
require: function(libraryName) {
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
},
...
Personally I try to avoid all this confusion by rolling all my javascript into one file. If there's one page which requires a LOT of javascript which the other pages don't need, then just have two files - generally the page-specific JS can be loaded after the generic js without hassles anyway.
To roll the JS files into one, I use Dean Edwards's Javascript Packer, combined with a helper script that I described on my blog. It makes working with many JS files muuuuuch easier (for me at least), and the compression you get from packing the javascript is better.
I guess you could use document.write in your JS files to make sure they include whatever dependencies they're dependent upon, though I wouldn't really recommend it...

Categories