I want to run set of script only if a function is already defined, which is in an included JS file. I am using jQuery and created a custom plugin, which I am not including in all pages. Where as the script includes function call to the plugin in all pages as its a common file. I want to check whether the function is defined, only then need to execute those script.
JSFiddle example for given instance.
<!DOCTYPE html>
<html>
<head>
<title>Testing JS Function Typeof</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript">
/* This is a plugin code, included as script src */
(function($) {
$.fn.includedFunJqReady = function() {
console.log("You are in includedFunJqReady");
}
}(jQuery));
/* EO plugin code */
/* JS in page */
function fun1() {
console.log('fun');
function fun2() {
console.log('fun 2');
}
}
jQuery(document).ready(function(){
console.log("Type of includedFunJqReady is: " + typeof(includedFunJqReady));
$('body').includedFunJqReady();
});
</script>
</head>
<body>
<script type="text/javascript">
document.write("Type of fun 1 is: " + typeof(fun1));
document.write("<br />");
document.write("Type of fun 2 is: " + typeof(fun2));
document.write("<br />");
document.write("Type of includedFunJqReady is: " + typeof(includedFunJqReady));
</script>
</body>
</html>
I have also seen this question and answer, but I want to know how we can overcome this issue.