JCraine
JCraine

Reputation: 1424

Javascript at the bottom, function call in the body?

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!

Upvotes: 3

Views: 6895

Answers (5)

Mikelon85
Mikelon85

Reputation: 432

You can also call your function from html document:

<body onload="yourFunction()">

and define it in .js

Upvotes: 1

simon
simon

Reputation: 12922

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.

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123438

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

Upvotes: 2

Sagiv Ofek
Sagiv Ofek

Reputation: 25280

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");
}

Upvotes: 0

Logan
Logan

Reputation: 1694

$(document).ready(function() {
   // put all your jQuery goodness in here.
 });

check this url : ready

Upvotes: 0

Related Questions