0

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.

Vaishak
  • 462
  • 2
  • 6
  • 17
  • 2
    Define the function in the global scope and not inside another function. – Andreas Feb 15 '18 at 06:14
  • 2
    That makes no sense. `includedFunReady` cannot be called anywhere... – Jonas Wilms Feb 15 '18 at 06:19
  • @JonasW. You are right. I have updated the question. Removed that code. I have also updated the [JS fiddle](https://jsfiddle.net/Vaishak/jvLopgj5/), would like to know any way I can check whether `includedFunJqReady` is defined or not! As @Andreas said its not possible, how to overcome this issue here? – Vaishak Feb 15 '18 at 07:12
  • @Andreas @JonasW I have updated the JSFiddle, where I can call `includedFunJqReady` but cannot check typeof of same. Why is it so? – Vaishak Feb 16 '18 at 04:47
  • 1
    Still the same reason: [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript), [Functions :: Eloquent JavaScript](http://eloquentjavascript.net/3rd_edition/03_functions.html) – Andreas Feb 16 '18 at 08:55

0 Answers0