I suppose you know that Javascript does not have preprocessor directives like C / C ++, but you can use regular if , which are evaluated at runtime as follows:
if (typeof myFunc === "undefined") { var myFunc = function(a,b) {
or for a whole library of functions:
if (!window.controlUtilsDefined) { window.controlUtilsDefined = true; // put control library functions here function aaa() { // body here } function bbb() { // body here } }
or if you want to check based on some other variable:
var myFunc; if (debugMode) { myFunc = function(a,b) {
If you are worried that you have multiple copies of the same function names in the library that each control uses, which is not technically a problem in Javascript. The last one defined will be operational, but if they are all the same, that is technically not a problem. There will be only one definition in memory, since later definitions will replace earlier ones.
If you control the source of the controls, then it would be better to split the common utilities separately into your own JS file and include only this script utility file on the host page.
Or (with a bit more work, but without additional responsibilities for the main page), each control could dynamically load its utlities from an external JS file and check a known global variable to see if any other control loaded a common external JS .
source share