问题
Just a quick question, I'm following the practice of keeping all Javascript files at the bottom of the document before the closing body. However I want to call a function in the body, which would appear before the JS include, and thus fails.
Is there anyway to get this function to work without moving the files into the head?
Cheers!
回答1:
yes you can wrap your function with
window.onload = function() {
//call to your function here
};
but probably this solution is better if you can modify the bottom part of your page:
Stop paying your jQuery tax
回答2:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
check this url : ready
回答3:
You can also call your function from html document:
<body onload="yourFunction()">
and define it in .js
回答4:
yes, use $(document).ready()
function that woll be called after the dom loaded so all your js functions are known.
$(function(){
//do stuff here
}
but your jQuery file must be before that call.
if you don't wanna use jquery- it depends how you declare the function. there is a difference between if you use var or not. have a look on this sample:
function FunctionDefinitionOrder() {
assert(isRed(), "Named function definition doesn't matter");
assert(isGreen === undefined, "However, it's not the case with anonymous functions");
function isRed() { return true; }
var isGreen = function () { return true; };
assert(isGreen(), "Anonymous functions are known only after the definition");
}
回答5:
If you are not calling the function in the body onload event, you should be able to call the functions from anywhere on the page, even when the functions are on the bottom of the page. The browser loads all the functions found to the memory when loading the page, so all functions are available when the page is ready. If the function is not found, you either
- misspelled the function name when calling it (unlikely)
or
- there is an error in the JS between the script tags containing the function to be called
In the second case, check if there are any errors in the JS console. You can also try to replace the function call to another function enclosed in separate script tags, just outputting an alert message. If this call works but the call to your "real" function doesn't, there is an error somewhere in the JS code preventing the function from being loaded.
来源:https://stackoverflow.com/questions/10849188/javascript-at-the-bottom-function-call-in-the-body