How to include JavaScript files properly in (ASP.NET) project? - javascript

I have ASP.NET (4.0) web site which in turn has some JavaScript on it. As time goes I include more and more JS files into my aspx and ascx files. Usually I just add
<script type="text/javascript" src="/js/script1.js"></script>
That works fine for small add-ons, but in some cases script1 references to script2 and I need to add one more reference IN EACH PLACE where script1 is used.
Is that the proper way to include JS files? Or I would better load script2.js from script1.js (How do I include a JavaScript file in another JavaScript file?) that will guarantee it will be always included?
Could you please recommend references on the "best practice" with regards to this topic. I've googled for some, but found way too many links and really sank...
Thank you for your help!

The best way I can think of is to base your forms on a MasterPage and then reference all of your js file in the head section of your MasterPage.

Related

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 a single javascript file from multiple files

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.

CDN / and or Hosting js and css files on a server

so id like to link a refernce to a couple js files if possible, but im not sure i could go about doing this so i can use it
<script type=text/javascript src=http://mylinkedjs></script>
and call i from my jquery.
Anyone know how this is possible?
Let me try to rephrase your question.
I want to include some JavaScript files from another server on my page, and call functions from those files in my own jQuery code. Is this possible?
That’s certainly possible. Once you’ve included a JavaScript file on your web page (like you did in the question), the global variables it creates are accessible to any other JavaScript running on that page, regardless of which server the JavaScript file was loaded from.
This is often how jQuery itself is included on pages: by linking to a copy of jQuery on a big CDN, e.g.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
See http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery
<script type="text/javascript" src="http://wherever.com/linked.js">

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

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.

Keeping my jQuery code away from the html files

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.

Categories

Resources