-1

I am taking a page that does not have jquery referenced in the dom. I need to use some of the jquery functionality, so i figured the best bet is to inject jquery into the existing dom. I got the function idea from Load jQuery with Javascript and use jQuery and How to include jQuery dynamically in any website using pure javascript ....none of these solutions seem to work for me. I am still getting an error not recognizing the jquery selector.

(function() {
    function getScript(url, success) {
        var script = document.createElement('script');
        script.src = url;
        var head = document.getElementsByTagName('head')[0],
            done = false;
        // Attach handlers for all browsers
        script.onload = script.onreadystatechange = function() {
          if (!done && (!this.readyState
               || this.readyState == 'loaded'
               || this.readyState == 'complete')) {
            done = true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
          }
        };
        head.appendChild(script);
    }
    getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js',function() {
        // Yay jQuery is ready \o/
    });                         


    cards = $('div:first');
    $('body').empty().append(cards);

    // Delete first and second child divs

    first = $('div:first div:first');
    $('div:first div:first').css('position', '').css('left', '').css('z-index', '').css('height', '250px').remove();

    second = $('div:first div:first');
    $('div:first div:first').css('position', 'relative').css('left', '').css('z-index', '').remove();

    $('body').empty().append(first).append(second);
    })();
Community
  • 1
  • 1
Jacob Alley
  • 767
  • 8
  • 34
  • 2
    You're supposed to move your own code into the callback, to where it says `// Yay...`. Only then is your code run *after* jQuery was loaded. –  Dec 05 '16 at 21:07
  • wel;l thats embarrassing...feel free to answer and ill accept – Jacob Alley Dec 05 '16 at 21:10
  • There is no such property "onreadystatechange" on script element, I think it is misleading information, just "onload" is enough. Here answer from Chris G is acceptable. Here is the plunker for the same https://plnkr.co/edit/WYV7PQDX9wJTjnVfQENa?p=preview – Sachin G. Dec 06 '16 at 03:50

1 Answers1

1

You're supposed to move your own code into the callback, to where it says // Yay.... Only then is your code run after jQuery was loaded.

getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js', function() {
    // Yay jQuery is ready \o/

    $('body').empty().append($('div:first'));
    // Delete first and second child divs
    for (var i = 0; i < 2; i++) {
        $('div:first div:first').remove();
    }
});