如何注入jQuery,并在同一bookmarklet中使用它? [英] how to inject jQuery and use it in the same bookmarklet?

查看:57
本文介绍了如何注入jQuery,并在同一bookmarklet中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下书签将jQuery成功地注入页面:

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));

有没有办法在同一bookmarklet中使用刚注入的jQuery?我尝试将 console.log(jQuery.toString())放在apend部分之后,但这没有用.在我看来,只有在完成书签后才能使用jQuery.

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.

推荐答案

使用新脚本元素的 onload 回调来初始化您自己的jQuery代码

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>

这篇关于如何注入jQuery,并在同一bookmarklet中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆