我可以使用以下小书签成功地将 jQuery 注入(inject)页面:
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));
有没有办法在同一个书签中使用刚刚注入(inject)的 jQuery?我试着把
console.log(jQuery.toString())
在追加部分之后,但它没有用。在我看来,jQuery 只能在小书签完成后才能使用。
最佳答案
使用onload
新脚本元素的回调以初始化您自己的 jQuery 代码
(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>
关于javascript - 如何注入(inject) jQuery 并在同一个书签中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58473252/