I have a question about a global script, I am using the following script right now, as these functions are used globally on every page. (before I have the same functions as the function unit converterdefined in 8 places, now I move it to the global script, so I only define it once.)
My question is: is this really the right way or best practice? I really need them to be defined globally and loaded before other scripts call these methods.
I searched, and an article like this suggests using 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 closure.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
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();
}
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":
out.q = (q * b);
out.p = (p / b);
break;
case "10":
out.q = q;
out.p = p;
break;
case "11":
out.q = (q * 100);
out.p = (p / 100);
break;
case "12":
out.q = (q * 2204.62262);
out.p = (p / 2204.62262);
break;
case "136":
out.q = (q * wb);
out.p = (p / wb);
break;
}
return out;
}
</script>
</head>
<body>
...
</body>
source
share