我可以使用以下书签将jQuery成功地注入页面:
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())
放在暂停部分之后,但是没有用。在我看来,只有在完成书签后才能使用jQuery。
使用新脚本元素的onload
回调来初始化您自己的jQuery代码
(function(doc) {
function doStuff() {
console.log('jQuery version ', $.fn.jquery, ' loaded')
$('h1').text('Updated Title');
}
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>