call a javascript method in another .js file
what is the rule around calling functions from one js to anot开发者_Python百科her ? I thought that this worked but i am not running into issue (figured it out through firefox) that a function in another js file doesn't seem to be recognized in my first js file.
Is there some rule around ordering or some trick you have to do to get this to work?
It has to be accessible in the global scope somewhere. For example:
// file1.js
function hello() {
alert("Hello, world!");
}
// file2.js
$(function() {
hello();
});
Likely, you have something like this:
// file1.js
$(function() {
function hello() {
alert("Hello, world!");
}
// ...
});
// file2.js
$(function() {
hello();
});
hello
is only in scope of the closure defined in file1.js
. Therefore, to access it in file2.js
, you'd have to export it to somewhere where file2.js
can get at it:
// file1.js
$(function() {
function hello() {
alert("Hello, world!");
}
window.hello=hello;
});
// file2.js
$(function() {
hello();
});
Also, the script where the function is defined must be loaded, parsed, and executed before the function can be called from another script.
Are you calling the function in an event handler, or immediately when the javascript file is loaded? If it's not in an event handler, then load order is important. If you have circular dependencies, you may need to delay some of the initialization with a "DOM ready" or window.onLoad
listener.
The browser parses the javascript files in the order they appear in the HTML. So if a function that is excecuted in the first file relies on a function that is in the second file it won't work. If you use $(function() {}); for example with jQuery this is instructing the javascript to wait until the onload event is fired from the window object. This ensures all the elements on the page have been loaded prior to execution.
精彩评论