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
To write a JavaScript, you need a web browser and either a text editor or an HTML editor. Once you have the software in place, you can begin writing JavaScript code. To add JavaScript code to an HTML file, create or open an HTML file with your text/HTML editor.
JavaScript allows us to write our own functions as well. This section explains how to write your own functions in JavaScript.
While other platforms, like Android or iOS, clearly state what a library is, what format it must have and how it should be integrated into a project, JavaScript doesn't provide any built-in mechanism.
Ordinary I use something like this to define separate module.
LibName= window.LibName || {};
LibName = function () {
var yourVar1;
var yourVar2;
publicFunc1 = function() {
};
privateFunc2 = function() {
};
return {
"publicFuncName" : publicFunc1
}
}();
In HTML it could be called like LibName.publicFuncName()
Also, look at Module Pattern here - http://addyosmani.com/resources/essentialjsdesignpatterns/book/
UPD:
Now ES6 is quite ready-for-production and the answer should be updated:
class MyLib {
constructor() {
this.foo = 1;
this.bar = 2;
}
myPublicMethod1() {
return this.foo;
}
myPublicMethod2(foo) {
return foo + this.bar;
}
}
const instance = new MyLib();
export { instance as MyLib };
And when you need it:
import { MyLib } from './MyLib';
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With