Change: defer page script injection. Try to inject to head (#584)

This commit is contained in:
eight 2018-11-28 12:57:44 +08:00 committed by Rob Garrison
parent a1b17bb553
commit 43a4671c64

View File

@ -65,10 +65,9 @@ const APPLY = (() => {
// Since it's easy to spoof the browser version in pre-Quantum FF we're checking // Since it's easy to spoof the browser version in pre-Quantum FF we're checking
// for getPreventDefault which got removed in FF59 https://bugzil.la/691151 // for getPreventDefault which got removed in FF59 https://bugzil.la/691151
const EVENT_NAME = chrome.runtime.id; const EVENT_NAME = chrome.runtime.id;
const usePageScript = CHROME || isOwnPage || Event.prototype.getPreventDefault ? let ready;
Promise.resolve(false) : injectPageScript();
return (el, content) => return (el, content) =>
usePageScript.then(ok => { checkPageScript().then(ok => {
if (!ok) { if (!ok) {
const disabled = el.disabled; const disabled = el.disabled;
el.textContent = content; el.textContent = content;
@ -83,6 +82,14 @@ const APPLY = (() => {
} }
}); });
function checkPageScript() {
if (!ready) {
ready = CHROME || isOwnPage || Event.prototype.getPreventDefault ?
Promise.resolve(false) : injectPageScript();
}
return ready;
}
function injectPageScript() { function injectPageScript() {
const scriptContent = EVENT_NAME => { const scriptContent = EVENT_NAME => {
document.currentScript.remove(); document.currentScript.remove();
@ -125,7 +132,7 @@ const APPLY = (() => {
script.src = src; script.src = src;
script.onerror = () => resolve(false); script.onerror = () => resolve(false);
window.addEventListener(EVENT_NAME, handleInit); window.addEventListener(EVENT_NAME, handleInit);
document.documentElement.appendChild(script); (document.head || document.documentElement).appendChild(script);
return promise.then(result => { return promise.then(result => {
script.remove(); script.remove();
window.removeEventListener(EVENT_NAME, handleInit); window.removeEventListener(EVENT_NAME, handleInit);