external js-files don't know each other - javascript

I have a very long external JS-file which I want to split in 2 seperate JS-files. The problem with this is, that file_1.js doesn't know the functions of file_2.js anymore. Is there something special I don't have in mind when I'm doing this.
<script src="js/file_1.js"></script>
<script src="js/file_2.js"></script>
head of my html.
and I'm loading every content in a document ready.
$(function() { some code in both });
Cheers

Javascript files can only access code from files that are loaded before them. In this example file2 can access functions in file1, but not the other way around.
If they each need to access each other, you have a circular dependency. When this happens, it usually means your two files should really just be one big one.

As previously stated, calling the external js file which declares the functions before the external js which calls the functions is what you need to do.
Have you tried calling one of the functions from within the dom? If that fails as well, there may be issues with how you broke up the js.
<script src="js/file_2.js"></script>
<script src="js/file_1.js"></script>
vs
<script src="js/file_2.js"></script>
<script>
$(document).ready(function(){
someFunctionWithinFile_2();
});
</script>

Related

How to use functions from another js file in a js file?

I am writing a HTML page that loads two js files. The two js files both use function a(), so I guess that if I can create the third js file and throw same function a() into that file, the browser might load faster because it doesn't have to load the same function twice. So can somebody tell me if I am on the right track about this, and how to load functions from different js file?
Thank you!
Long answer - all your code shares the same global scope.
So if you define a function a at the top-level scope of a file - there is no need to include a into each. There are exception, of course.
On the contrary - including it only once and only when needed would actually benefit you, in common case - since each of the consequitive files would be smaller, and as such require shorter time to download, thus making your site "faster".
There is some reading you might benefit from:
Scope:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope
http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/
Relevant Module Pattern:
http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
Common implementation of an AMD spec:
http://addyosmani.com/writing-modular-js/
http://requirejs.org/docs/whyamd.html
So can somebody tell me if I am on the right track about this
You might be. If the function is absolutely enormous, it might improve performance (in terms of not having to download the function twice; the effect on execution time is negligible), but there are better reasons to split it out into a separate file:
You only have to change it once if you need to change it.
The browser can cache it separately.
As for loading it in browser JavaScript, just add another <script> element for it:
<script src="a.js"></script> <!-- Contains a() -->
<script src="b.js"></script> <!-- Uses a() -->
<script src="c.js"></script> <!-- Also uses a() -->
To accomplish what you are looking for, move function a() into its own file (3) and remove it from files 1 & 2. Then when referencing your javascript files inside your HTML, include this 3rd file first.
One caveat is that you want to make sure function a() is the exact same.
For optimal performance, you want to combine all of your JS into one file and then minify. A good place to start is using Chrome's Page Speed (F12 > Page Speed tab)

Calling functions from js file to html page

I have three js files for all of my webpages, and I have pre-defined sets of functions to call for each web page. Could I move all of these functions to a new js file which would make then calls to other functions in a different js file? I read about rloader at http://code.google.com/p/rloader/, but I am not sure if I could use it.
<script src="js/rootNameSpace.js"></script>
<script src="js/jquery-min.js"></script>
<script src="js/ui.js"></script>
<script src="js/form.js"></script>
<script type="text/javascript">
console.dir(com);
com.rela.form.helloWorld1();
com.rela.form.helloWorld2();
</script>
Yes. If you move the contents of the script tag to a file with the path "js/main.js" and then added a script
<script src="js/main.js"></script>
after the other scripts, it will be able to call the functions. Including an external script is equivalent to having the text from that script inline in the file.
Scripts can read the contents of previous scripts so having multiple scripts on the page is similar to concatenating them all into a single file, which means that if you add a script below the other scripts it will be able to "see" everything in the others
With regard to questions about rloader
rloader does lazy loading to pull in scripts when you need them.
For more on lazy loading
And you can learn about rloader from its site (I'm no expert on that)
For what its worth I would not recommend using rloader if you really only have 4 scripts on one page. Its overkill. If you're planning on having a much bigger project, then you can use it or the more popular requirejs to manage your scripts across pages.
If you have dynamic generated pages you can have different names/actions/controllers whatever.
Then you can
echo '<script type="text/javascript">$(document).ready(function(){'.$page_name.'();});</script>';
Then you can declare global functions in any JS file, yes you can have any number of JS files, and splited in any way you want, they are all global.
function name1(){...};
If you have a big application with many JS files you can split then into more files, in a single folder, then add a minify plugin to "collect" them in a single output file (or a JS builder).
rloader is a dynamic loading script, basically Injects JS files in your document (http://ntt.cc/2008/02/10/4-ways-to-dynamically-load-external-javascriptwith-source.html). I don't recommend using it, except if you have a very big application and use a MVC http://coding.smashingmagazine.com/2012/07/27/journey-through-the-javascript-mvc-jungle/ that loads only the current module.
It is always better to put code in separate files (as far as they are less in size and count). This will allow to be cached by browser $(document).ready will keep you safe for other dom elements that are not loaded.
Create something like this:
<script src="js/rootNameSpace.js"></script>
<script src="js/jquery-min.js"></script>
<script src="js/ui.js"></script>
<script src="js/form.js"></script>
<script src="js/pages/some-page.js"></script>
some-page.js
$(document).ready(function(){
console.dir(com);
//call to function form.helloWorld1
com.relais.form.helloWorld1();
com.relais.form.helloWorld2();
});
A better option would be combine files (If they are common on each page). rootNameSpace.js, jquery-min.js, ui.js, form.js into a file say common.js. You can use Google Closure to do that.
<script src="js/common.js"></script>
<script src="js/pages/some-page.js"></script>

Yabble - accessing functions loaded by yabble

Am having a problem with Yabble that I have not been able to solve.
From within my main html I load all of my js using yabble
<script>
require.setModuleRoot('./javascript/');
require.run('main')
</script>
I have a bunch of js (gamejs related). In one file I have function changeSimulationSettings(). Later within the same page I want to take user input and access the gamejs objects and change their state. The problem I am having is that I am unable to call changeSimulationSettings. It is not defined within the current context. Yabble does so much magic I am unable to find where it is defined or how to access.
<div>
<button type="button" onclick="updateSettings()">Update-Settings</button>
</div>
<script type="text/javascript">
function updateSettings(){
// access function defined in a js loaded by yabble
i.e. changeSimulationSettings()
}
</script>
All of the js is definitely being loaded as I have got functions calling each other from different files which does work. However, I am unable to call anything from js embedded within the entry web page.
Any help would be appreciated as I have been stuck on this one for hours and hours.
Thanks,
Code defined in modules is isolated and not available globally.
I would do it the other way around: from within a module attach an event handler. Do not use "onclick=" but instead in a module, where you have changeSimuSettings available, do something like this (e.g. using jquery or plain DOM):
$('button').click(changeSimulationSettings)
This is cleaner and you are not leaking globals. If you insist on doing it your way, you could export changeSimulationSettings to global and use the code you already have. Like so (I would not recommend that):
window.changeSimulationSettings = function() {...

Use Jquery inside JS file?

I have created an external JS file, this JS file contains some methodes that uses JQuery, i can't seem to find a way to refernece the JQuery file on JS file and user it there. Any help would be appreciated
Two things are important to reach your goal:
Include the javascript files. Include both files in your HTML via a script-tag, starting with jQuery to make sure it is loaded when used by your javascript.
Ensure jQuery. This is something way to less people tell you. If you write JS and jQuery for a long time, sooner or later you'll encounter a case where something is overwriting the $-variable. The $-variable is used by jQuery and everyone coding with it because of the obvious fact that it's just one char. However, jQuery doesn't have any "rights" or something for the $-variable, so basically anything or anyone could overwrite it. So I recommend your own javascript file looks like this:
(function($)
{
// your coding starts here.
})(jQuery);
You probably already encountered this when dissecting jQuery plugins from people who know what they're doing. It creates an anonymous function that takes one parameter which will be know by $ inside the function. The function is then immediately called and hands over the jQuery function. This way you can be sure that, whatever happens outside this function, inside of it $ stands for jQuery.
In your HTML file, include the jQuery file first and then your file:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="myfile.js"></script>
As long as you include the jQuery core in your HTML, the global jQuery object is available in any of your scripts. Is there a specific problem you're having?
You must write a piece of script (plain JS) that checks for the presence of jQuery, if not, it must append a script reference to the page pointing to a jQuery file (or Google CDN) to include jQuery. After that, you can use jQuery in the rest of your script.
I think it will involve some interval that checks wheter the jQuery object is present or not and waits with executing the rest of your code till that it the case.
Google for this, I'm sure there is something out there.

setting a source for all jquery in an application

Im new to Jquery but it turns out I used it quite a bit in my last application. My problem now is that its reloaded every single time one of my pages is loaded/reloaded. Is there an efficient way to reference it like we do a css or javascript file? for example:
<script type="text/javascript" language="javascript" src="js/behavior.js"></script>
I would really like to be able to do this with the jquery...because its quite a mess when you look at the source code. To avoid confusion: I already have jquery loaded. For example...this is already in my html:
<script src="js/jquery.min.js" type="text/javascript"></script>
What Im trying to cache is all of the code I've built off Jquery. For example:
$('#needDelete').slideDown('slow');
I have a bunch of these that need to be put into a file if that's even possible! Thanks!
jQuery is a JavaScript library. It consists of a single JavaScript file. All the documentation for it says to use <script src="..." to load it.
Update in response to edit:
The JavaScript you write that calls jQuery functions is still JavaScript and can be referenced from an external file just like any other JavaScript.
Yes, of course you can save your JavaScript code in a separate file (whether based on jQuery or not). Just keep your code separated and put it eg. in main.js file, then put a tag after jQuery script tag:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
Just for consistency and improved maintainability, it is easier if all the code is in one place than when it is often referenced within HTML like that:
show popup
Instead of the above you could do this in a separate JS file:
$('#a1').click(function(event){
event.preventDefault();
$('#popup').show();
}):
(of course the above code should be enclosed within onload or ondomready handler, so the code searches for elements after they become accessible - in case of jQuery and ondomready you can simply use: jQuery(function(){/* your code executed when DOM is ready */});)
I would refer jQuery from a CDN. This will allow the browser to do parallel download along with other resources from my domain, thus save some load time.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
The cdn version will be usually cached in your browser.
I don't get this question. What do you want?
I tried opening a file called custom.js. I dumped all of the jQuery
code into it and then referenced it. Nothing worked. Does there need
to be something additional in the reference page itself?
Why would you do that? You save some loading by decrease the number of different files, but the difference between one and two files is minimal.
Instead, do as Frederik Creemers suggested. Juse the jQuery-library at googleapis.com. The file is cached, meaning it will not load every single time a user visits your page. Only when the cache expires (not 100% sure how long this is). In addition, this library is used by many other sites, so you might be lucky and the user downloads it somewhere else and has it ready for use when going to your page.
Again, what you are asking (if I understood correctly) is pointless.
download jquery, and reference it like this:
<script src='jquery.js'></script>
Or, for an even better option, you can use google's cdn. This means that if a user comes to your site, and has already visited a site which uses the cdn, it will already have jquery cached.
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
and for the best option, to protect against the possibility of downtime of the cdn, combine the local copy and the cdn like this:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script>
if(!window.jQuery){
script = document.createElement('script');
script.src='js/jquery.js';
document.head.appendChild(script)
}
</script>

Categories

Resources