How to create a javascript library of generic functions

I wrote a bunch of javascript functions in my html file between tags, but now I want all my functions to be in a separate JS file, so I can reuse the JS file for other html pages, so I only need to include the JS file.

This is how my functions look:

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

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

Will it work if I just copy these functions into a JS file and include the JS file in my html document, can I call such functions as usual?

Grtz

+6
source share
2 answers

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

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

The document.ready event will not be fired before all scripts connected in this way are loaded and executed, so all functions defined in it will be available when this happens.

To avoid hassle with other libraries, you can put all of your functions into a global object that 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, access them as follows:

 myLibrary.makeStartRefresher(refresher, 1000); 
+26
source

Normal I use something like this to define a separate module.

 LibName= window.LibName || {}; LibName = function () { var yourVar1; var yourVar2; publicFunc1 = function() { }; privateFunc2 = function() { }; return { "publicFuncName" : publicFunc1 } }(); 

In HTML, it can be called similar to LibName.publicFuncName()

Also, check out the module template here - http://addyosmani.com/resources/essentialjsdesignpatterns/book/

UPD:

ES6 is now 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'; 
+16
source

Source: https://habr.com/ru/post/943881/


All Articles