Question

I am trying to dynamically load a jQuery plugin by calling "getScript" - but it doesn't seem to recognize the initialization function of the plugin.

However, if I simply include the plugin by creating a script tag, the plugin works fine. I cannot use a static script tag because the final product is loaded dynamically via JavaScript that is put on a page that I do not have control of.

I've demonstrated this below with a plugin called jScrollPane:

The first head is the working copy, and the second is the dynamic way. When the dynamic way is run, there is an error that $('#content').jScrollPane() is not a function!

   <head>
        <link type="text/css" href="http://jscrollpane.kelvinluck.com/style/jquery.jscrollpane.css" rel="stylesheet" media="all" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://jscrollpane.kelvinluck.com/script/jquery.mousewheel.js"></script>
        <script type="text/javascript" src="http://jscrollpane.kelvinluck.com/script/mwheelIntent.js"></script>
        <script type="text/javascript" src="http://jscrollpane.kelvinluck.com/script/jquery.jscrollpane.min.js"></script>

    </head>



    <head>
        <link type="text/css" href="http://jscrollpane.kelvinluck.com/style/jquery.jscrollpane.css" rel="stylesheet" media="all" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://jscrollpane.kelvinluck.com/script/jquery.mousewheel.js"></script>
        <script type="text/javascript" src="http://jscrollpane.kelvinluck.com/script/mwheelIntent.js"></script>
        <script type="text/javascript">
            function setScroll() {
                $(function () {
                    $('#content').jScrollPane();
                });
            }
        </script>
<script type="text/javascript">
        $.getScript("http://jscrollpane.kelvinluck.com/script/jquery.jscrollpane.min.js", setScroll());
    </script>
</head>

The only thing that has changed is that the jquery.jscrollpane.min.js is being loaded by .getScript and then the actually initialization occurs in the callback function.

Was it helpful?

Solution

You want to pass the setScroll function to getScript, but instead you're actually calling it and passing whatever it returns. Lose that final ().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top