How to include js file in another js file? [duplicate] - javascript

This question already has answers here:
Including a .js file within a .js file [duplicate]
(5 answers)
Closed 3 years ago.
How can I include a js file into another js file , so as to stick to the DRY principle and avoid duplication of code.

You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});

I disagree with the document.write technique (see suggestion of Vahan Margaryan). I like document.getElementsByTagName('head')[0].appendChild(...) (see suggestion of Matt Ball), but there is one important issue: the script execution order.
Recently, I have spent a lot of time reproducing one similar issue, and even the well-known jQuery plugin uses the same technique (see src here) to load the files, but others have also reported the issue. Imagine you have JavaScript library which consists of many scripts, and one loader.js loads all the parts. Some parts are dependent on one another. Imagine you include another main.js script per <script> which uses the objects from loader.js immediately after the loader.js. The issue was that sometimes main.js is executed before all the scripts are loaded by loader.js. The usage of $(document).ready(function () {/*code here*/}); inside of main.js script does not help. The usage of cascading onload event handler in the loader.js will make the script loading sequential instead of parallel, and will make it difficult to use main.js script, which should just be an include somewhere after loader.js.
By reproducing the issue in my environment, I can see that **the order of execution of the scripts in Internet Explorer 8 can differ in the inclusion of the JavaScript*. It is a very difficult issue if you need include scripts that are dependent on one another. The issue is described in Loading Javascript files in parallel, and the suggested workaround is to use document.writeln:
document.writeln("<script type='text/javascript' src='Script1.js'></script>");
document.writeln("<script type='text/javascript' src='Script2.js'></script>");
So in the case of "the scripts are downloaded in parallel but executed in the order they're written to the page", after changing from document.getElementsByTagName('head')[0].appendChild(...) technique to document.writeln, I had not seen the issue anymore.
So I recommend that you use document.writeln.
UPDATED: If somebody is interested, they can try to load (and reload) the page in Internet Explorer (the page uses the document.getElementsByTagName('head')[0].appendChild(...) technique), and then compare with the fixed version used document.writeln. (The code of the page is relatively dirty and is not from me, but it can be used to reproduce the issue).

You need to write a document.write object:
document.write('<script type="text/javascript" src="file.js" ></script>');
and place it in your main javascript file

It is not possible directly. You may as well write some preprocessor which can handle that.
If I understand it correctly then below are the things that can be helpful to achieve that:
Use a pre-processor which will run through your JS files for example looking for patterns like "#import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)
If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.
Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.
JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( #import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".
Hope it helps.

Related

Async js files load in Rails (with JQuery)

Does anyone tried to play with async: true for js includes in Rails? I mean it works great but just if you are not using jQuery. If you do, then you could face some strange effects like "$" is not defined and etc. There is plenty of articles how to avoid that, but all of them seems to be done with no Rails in mind. For example, this one: http://www.yterium.net/jQl-an-asynchronous-jQuery-Loader
Seems like I have to move jQuery from applicaction.js - means out from being putted into one big file with other JS I have.
Just wonder is there some "rails-way" of loading js asynchronously since Google is strongly recommended to do that (it is affected a page load speed a lot, and as a result - your Page Rank)?
This is a browser issue, not a Rails issue. In short, you can't do this on most browsers. This will cause a dependency error, which is what the error points to. One solution is to add the dependency in a file with all the dependent code.
However, this problem has been solved in ES6, using JavaScript imports. There is a guide on how to implement these imports in another answer here. See How do I include a JavaScript file in another JavaScript file? for that info.

Organizing library dependencies in JavaScript best practice

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.

Loading and running js code when page loading finished (unobtrusive way)

I'd like to separate my JS code from HTML as much as possible and I can see several patterns for that.
1) I can use
$(document).ready(function() {...})
just before closing body tag
2) I can just put js code like
new FormValidationHandler()
in script tag just before closing body tag
3) I can point external js file containing initialization like $(document)ready or new FormValidationHandler in script tag
4) there is also a way to use self-invoking function but don't know if it maps to this problem
My question is which way is preferred?
Second one is that there are two places I can put my external scripts into the web page:
in the head tag
in the body tag (usually at the end)
Should head contain only code that doesn't have to run on page load? Then that code should be placed in body?
there is how I like to do. It's probably not perfect, but I like it this way :
Script location in the HTML document :
Every script loaded at the end of the HTML doc, just before the closing body.
There's one exception : the script that handles the FOUC (modernizr for example). This script must be in the head.
I don't see any other reasonable exceptions.
Scripts organization :
Their's two cases for this, in my opinion : If you work with an Hypertext document, or a web app (Maybe this could need some more explanations, but it would be long :p ). I rarely worked for web apps, so I don't yet have a validated organization for this. But I think in a web app you can probably use some script loading libraries like requirejs and it will probably be more useful than for simple web pages.
For a Hypertext document (most web pages), I like to distinguish two kind of scripts : libraries and what I call in french "script d'interfaçage" ("linking script" could probably be a good translation...).
Libraries are, as the name says, scripts that loads libraries in the javascript environment, but doesn't DO anything.
linking script is made to link those libraries to the specific HTML doc.
For me, in a perfect world, there should be as much library scripts as you which but only one linking script for each HTML doc. In this script you'll find the $(document).ready call if you're using jQuery, and all the content of this script should be very very very simple. Ideally there should be, in the document ready function, only instructions like :
$('my selector').MyPlugin({
option1:'value',
option2: 'value'
});
This type of instruction is really a simple link between the HTML doc and the JS library, and it's very simple to read and understand.
Over this organization, you can than do any kind of packaging to reduce the number of js files to be loaded. This packaging have to be optimized for client caching and limiting HTTP requests etc...
External files or inline scripts ?
Personally, I prefer to use external files for all scripts, but generally I use one inline script tag to declare some variables needed for some libraries (your key for your ad service etc...).
Loading of external libraries
One last specific case : When you have to load a script from another host. Generally, you can't tell if the script will load or not, because you can't tell if the other server is up or not, and if it will be slow or fast... You can't tell exactly what this script will do, so it could break your page...
Loading scripts from other hosts can really create problems, and this is why I recommend loading them asynchronously, once your page is fully loaded, with as much controls as you can.
To do this, I personally developed a library dedicated to loading libraries (maybe one day I'll publish it on gitHub, when I have some time).
For example, I use this script to load Facebook google+ ou twitter APIs, or any other external libs like stat counter or ads services.

How to Include JavaScript on a Public Facing Website?

I am building a public facing website and I am using a lot of jQuery and jQueryUI. What I have noticed is that most site on internet that use jQuery and jQueryUI don't have code like this in their pages.
<script type="text/javascript">
$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
$( "input:submit" ).button();
});
</script>
I know this is a simplistic example but most sites, for example SO have only one obfuscated js file included for all the pages. It doesn't even seem like they use $(document).ready anywhere. On my current site it seems like I would need to include a js file for each page. My question is how is it suppose to be done and is there a best practice on how to use/include javascript in a page?
You wouldn't see the famous document.ready because most of the code is compressed usually into one big file for caching purposes. Just include your js at the end of the body like:
<script type="text/javascript" src="site.js"></script>
so this can be cached once and for all for every page.
According to W3C you could put scripts almost anywhere: http://www.w3schools.com/js/js_whereto.asp
So where should you put them?
Ege is right to say that you should put them as far down the page as possible because it will enable the browser to load more in parallel up front before it gets to the 'blocking' scripts. See here for more detail: http://developer.yahoo.com/performance/rules.html#js_bottom
Also, it is nearly always a good idea to put your scripts (and CSS) into external files so the browser can cache them tus saving the user from having to download them with the page each time.
Personally, I always use a CDN for script frameworks such as jQuery and the like as they can deliver external resources quicker than you probably can. Also the likelyhood of the browser having already cached jQuery for another site from the same CDN is far more likely. More detail here: http://code.google.com/apis/libraries/devguide.html
Finally, there's nothing wrong with using $(document).ready, but just be aware that this could affect the site's responsiveness and its pros may not outweight its cons. Again, more detail here: http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/
Hope this helped.
Whether you include the 'site.js' file at the top or bottom doesn't matter, unless your javascript is doing document.write to put something on the page. Then of course at the top would be desired. Some like it at the bottom so that the rest of the page will load before downloading the js file, which can sometimes delay the page load if it is a large file.

Lazy loading and dependency resolution

some time ago, I was reading an article(a library built by some guy) about how his library can do
lazy loading of JS
resolve dependencies between JS
(typically encountered when trying
to "include" one js from another)
include files only once. thought
specified multiple times regardless
of how they are called (either
directly specifying it as file or
specifying it as one of the
dependencies)
I forgot to bookmark it, what a mistake. Can some one point me to something which can do the above. I know DOJO and YUI library have something like this, but I am looking for something which I can use with jQuery
I am probably looking for one more feature as well.
My site has asp.net user controls
(reusable server side code snippets)
which have some JS. Some of them get
fired right away, when the page is
loading which gives a bad user
experience. Yahoo performance
guidelines specify that JS should
be at the bottom of the page, but
this is not possible in my case as
this would require me to separate the
JS and the corresponding server side
control into different files and
maintenance would be difficult. I
definitely can put a jQuery
document.ready() in my user control
JS to make sure that it fires only
after the DOM has loaded, but I am
looking for a simpler solution.
Is there anyway that I could say "begin executing any JS only after DOM has loaded" in a global way than just writing "document.ready" within every user control ?
Microsoft Research proposed a new tool called DOLOTO. It can take care of rewriting & function splitting and enable the on-demand js loading possible.
From the site..
Doloto is a system that analyzes
application workloads and
automatically performs code splitting
of existing large Web 2.0
applications. After being processed by
Doloto, an application will initially
transfer only the portion of code
necessary for application
initialization. The rest of the
application's code is replaced by
short stubs -- their actual function
code is transferred lazily in the
background or, at the latest,
on-demand on first execution.
OK I guess I found the link
[>10 years ago; now they are all broken]
http://ajaxian.com/archives/usingjs-manage-javascript-dependencies
http://www.jondavis.net/techblog/post/2008/04/Javascript-Introducing-Using-%28js%29.aspx
I also found one more, for folks who are interested in lazy loading/dynamic js dependency resolution
http://jsload.net/
About the lazy-loading scripts thingy, most libraries just adds a <script> element inside the HTML pointing to the JS file to be "included" (assynchronously), while others like DOJO, fetches it's dependencies using a XMLHttpRequest and then eval's its contents, making it work synchronously.
I've used the YUI-Loader that is pretty much simple to use and you don't need the whole library to get it working. There are other libraries that gives you just this specific funcionality, but I think YUI's is the safe choice.
About your last question, I don't think there's something like that. You would have to do it yourself, but it would be similar to using document.ready.
i did in my framework a similar thing:
i created a include_js(file); that include the js file only if it isn't included reading and executing it with a synchronous ajax call.
Simply put that code in top of the page that needs dependencies and you're done!

Categories

Resources