And it works fine, but I am having the concern whether the scripts added to be executed in this manner are being executed asynchronously. If yes then it can happen that work.js runs even before jQuery (or other libraries which I may add in future).
That shouldn't really be a concern: you queue up scripts to be executed in a certain JS context, and that context can't have a race condition as it's single-threaded.
However, the proper way to eliminate this concern is to chain the calls:
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript({
file: 'thirdParty/jquery-2.0.3.js'
}, function() {
// Guaranteed to execute only after the previous script returns
chrome.tabs.executeScript({
file: 'work.js'
});
});
});
Or, generalized:
function injectScripts(scripts, callback) {
if(scripts.length) {
var script = scripts.shift();
chrome.tabs.executeScript({file: script}, function() {
if(chrome.runtime.lastError && typeof callback === "function") {
callback(false); // Injection failed
}
injectScripts(scripts, callback);
});
} else {
if(typeof callback === "function") {
callback(true);
}
}
}
injectScripts(["thirdParty/jquery-2.0.3.js", "work.js"], doSomethingElse);
Or, promisified (and brought more in line with the proper signature):
function injectScript(tabId, injectDetails) {
return new Promise((resolve, reject) => {
chrome.tabs.executeScript(tabId, injectDetails, (data) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message);
} else {
resolve(data);
}
});
});
}
injectScript(null, {file: "thirdParty/jquery-2.0.3.js"}).then(
() => injectScript(null, {file: "work.js"})
).then(
() => doSomethingElse
).catch(
(error) => console.error(error)
);
Or, why the heck not, async
/await
-ed for even clearer syntax:
function injectScript(tabId, injectDetails) {
return new Promise((resolve, reject) => {
chrome.tabs.executeScript(tabId, injectDetails, (data) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message);
} else {
resolve(data);
}
});
});
}
try {
await injectScript(null, {file: "thirdParty/jquery-2.0.3.js"});
await injectScript(null, {file: "work.js"});
doSomethingElse();
} catch (err) {
console.error(err);
}
Note, in Firefox you can just use browser.tabs.executeScript
as it will return a Promise.