0

I've been getting this error:

Uncaught ReferenceError: $ is not defined

I've done the basics right but still it show this. What am I doing wrong? Here is my script. I'm using DOM elements to create this.

var parenthead = document.head;
sjq = document.createElement("script");
sjq.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js";
parenthead.appendChild(sjq);

swt = document.createElement("script");
swt.src = "http://otexconnect.com/jquery.webticker.min.js";
parenthead.appendChild(swt);

$("#webticker").webTicker();

Here is my HTML

<ul id="webticker">
    <li id="item1">Some text</li>
</ul>

Any sort of help will be appriciated. Thanks

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
sajawalsz
  • 91
  • 7
  • Any reason why you load your scripts via JavaScript instead of using plain script tags? Also it's possible you're executing `$("#webticker").webTicker();` before jQuery has finished loading. – j08691 Apr 22 '16 at 14:39
  • Im writing a service in script form to be included from another website so i can not really write html tags directly. – sajawalsz Apr 25 '16 at 06:03

1 Answers1

1

You call a function that is not yet ready for use, you need a callback, did a load function, when all scripts are ready it will call the callback statement.

<ul id="webticker">
    <li id="item1">Some text</li>
</ul>
<script>
var libsToLoad = ['http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js',
        'http://otexconnect.com/jquery.webticker.min.js'];
    function load(array,cb){
        var ready = false;
        var lib = null;
        var parenthead = document.head;
        var totalItens = array.length;
        var loaded = 0;
        while(lib = array.shift()){
            console.log('lib',lib);
            var script = document.createElement("script");
            script.src = lib;
            parenthead.appendChild(script);
            script.onload = function(){
                    loaded++;
                    if(loaded == totalItens){
                        ready = true;
                        cb();
                    }
            };

        }

    }

    load(libsToLoad,function(){
        console.log('ready');
        console.log($);
        console.log($("#webticker li").html())
        //Make your logic here
    });
</script>
  • +1 for loading function. Now I know my html is loading first but still jQuery error is being occurred in my jquery.webticker.min.js file at the end line })( jQuery ); . Any idea why. Even though the jQuery file is included first and the version jquery.webticker.min.js requires is 1.4.0 or above and i have included 1.11.1 – sajawalsz Apr 25 '16 at 06:02
  • I tested here and the only way that happened this error, was without including the jQuery. I hope that you find answer. – Anderson Contreira Apr 25 '16 at 19:08