Calling functions from multiple files within a single load statement using jQuery
I'm trying to achieve the most basic include with jQuery
, that is loading functions from multiple files when the DOM is ready, but apparently it turned out not to be so trivial:
index.html
<script type="text/javascript" src="res/scripts.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert("Hello world!");
foo();
bar();
});
</script>
scripts.js
function foo(){
alert("Hello from foo!");
}
function bar(){
alert("Hello from bar!");
}
With alert("Hello world!");
being the only statement that executes as expected. The folder locations are checked, as worked with the previous strategy (window.attachEvent
)
I've tried moving the .ready()
statement to the scripts.js
file but that didn't helped much.
Any advice would me really appreciated. Thanks much in advance.
UPDATE
Currently I'm handling the function loading this way:
// Based on "Flexible JavaScript events" by John Resig: http://goo.gl/xLn4S
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
开发者_JAVA技巧obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
if ( obj.detachEvent ) {
obj.detachEvent( 'on'+type, obj[type+fn] );
obj[type+fn] = null;
} else
obj.removeEventListener( type, fn, false );
}
addEvent(window, 'load', foo);
addEvent(window, 'load', bar);
$(document).ready()
is executed after the dom is complete which can happen before the external javascript files are downloaded so foo and bar may not be defined yet.
I think it's just a typo. It's alert not altert:
function foo(){
alert("Hello from foo!");
}
function bar(){
alert("Hello from bar!");
}
Tools like Firebug can help with things like that.
First, add a unique number to the url you use to retrieve your javascript, as in:
<script type="text/javascript" src="res/scripts.js?111010101"></script>
to assure the browser retrieves the most current version of scripts.js. Then, every time the page is retrieved, generate a new unique version number. (At least during development)
Next, you need to assure that script.js has been loaded and correctly evaluated before you try to call its functions.
One way to do this would be to trigger a new, custom event at the bottom of script.js, on which you would set a handler to execute (in document.ready()).
Another way would be to load the script within the document.ready() handler before you tried to call any of its functions.
EDIT to add example:
<script type="text/javascript">
document.ready(function(){
alert('Hello World!');
$.getScript('res/scripts.js', function() {
foo();
bar();
});
});
</script>
精彩评论