Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  42] [ 2]  / answers: 1 / hits: 27470  / 11 Years ago, mon, april 29, 2013, 12:00:00

I have written a bunch of javascript functions in my html file between the tags but now I want all of my functions in a seperate JS file so I can re-use the JS file for other html pages so that I only need to include the JS file.



this is how my functions look like:



function makeStartRefresher(refresh, refreshTime) {
//function code
}
function readData(address){
//function code
}
function writeData(address, value, refreshCallback){....
........
........
........


These are written above my document.ready function, from where I call and use these functions.



Will it work if I just copy these functions to a JS file and include the JS file in my html document, will I be able to call the functions like normal?



Grtz


More From » html

 Answers
32

Just copy your JS functions into a .js file and include it like this in the <head> section of your HTML documents:



<script type=text/javascript src=mylibrary.js></script>



The document.ready event won't be fired before all scripts linked that way are loaded and executed, so all functions defined in it will be available when it happens.



To avoid nameclashes with other libraries, you can optionally put all your functions into a global object which serves as a namespace.



// mylibrary.js
var myLibrary = {

makeStartRefresher: function(refresh, refreshTime) {
//function code
},
readData: function(address){
//function code
}
...
}


and then when you use functions from your library, refer to them like this:



myLibrary.makeStartRefresher(refresher, 1000);

[#78539] Saturday, April 27, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbyallanh

Total Points: 693
Total Questions: 120
Total Answers: 101

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;