I have a question about the global script, I'm using the following script right now since those functions are used globally on every page. (before I have the same functions like unit converter function defined in 8 places, now I move it to the global script so I only define it once.)
My question is, is this a valid way or best practice to do? I really need them to defined globally and loaded before other scripts are calling those methods.
I have searched and article like this suggest not use global functions. https://www.w3schools.com/js/js_best_practices.asp
Avoid Global Variables
Minimize the use of global variables.
This includes all data types, objects, and functions.
Global variables and functions can be overwritten by other scripts.
Use local variables instead, and learn how to use closures.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
/*-----------------------------------------------------
global function for Set/Get Cookie
------------------------------------------------------*/
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
/*-----------------------------------------------------
global function for ...
------------------------------------------------------*/
function getLBS_Global(p, q, u, b, wb) {
if (b === null || wb === null) {
alert("Error in unit conversion, please retry");
}
var out = {};
switch (u) {
case "8": // A bushel
out.q = (q * b);
out.p = (p / b);
break;
case "10": // lbs
out.q = q;
out.p = p;
break;
case "11": // cwt
out.q = (q * 100);
out.p = (p / 100);
break;
case "12": // metric tonne
out.q = (q * 2204.62262);
out.p = (p / 2204.62262);
break;
case "136": // W bushel
out.q = (q * wb);
out.p = (p / wb);
break;
}
return out;
}
</script>
</head>
<body>
...
</body>