4

I can successfully inject jQuery to a page with the following bookmarklet:

javascript: void((function(doc) {
    if (typeof jQuery == 'undefined') {
        var script_jQuery = document.createElement('script');
        script_jQuery.setAttribute('src', 'https://code.jquery.com/jquery-latest.min.js');
        Node.prototype.appendChild.call(document.body, script_jQuery);
        console.log('jQuery included ^_^');
    } else {
        console.log('jQuery already included ...');
    }
})(document));

Is there a way to use the just injected jQuery within the same bookmarklet? I tried putting console.log(jQuery.toString()) after the apend part, but it didn't work. It seems to me that jQuery is only available for using after the bookmarklet finishes.

daremachine
  • 2,678
  • 2
  • 23
  • 34
SparedWhisle
  • 1,370
  • 2
  • 10
  • 20

1 Answers1

3

Use onload callback of the new script element to initialize your own jQuery code

(function(doc) {

  function doStuff() {
    console.log('jQuery version ', $.fn.jquery, ' loaded')
    $('h1').text('Updated Title').css('color', 'red');
  }

  if (typeof jQuery == 'undefined') {
    var script_jQuery = document.createElement('script');
    script_jQuery.src = 'https://code.jquery.com/jquery-latest.min.js';

    // call doStuff() after jQuery.js loads
    script_jQuery.onload = doStuff;

    doc.body.appendChild(script_jQuery);
    console.log('script_jQuery appended to body');
    
  } else {
    console.log('jQuery already included ...');
    // initialize your code using existing version
    doStuff();
  }
})(document)
<h1>Blank</h1>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • In Firefox, this always says "$.fn is undefined" when I run it on non jQuery websites. But when I type $.fn in browser console afterwards, it is defined... Does Firefox's onload not work properly? – Needs more jpeg Jan 30 '22 at 23:04
  • @Needsmorejpeg If you are having problem you should ask a new question and include all the specifics – charlietfl Jan 31 '22 at 01:18