Is it possible to get an event (or other way of knowing) when a specific script is loaded into a page?
E.g. I have a page action that should perform action if jQuery is present and have finished loading.
Is it possible to get an event (or other way of knowing) when a specific script is loaded into a page?
E.g. I have a page action that should perform action if jQuery is present and have finished loading.
I can think of two approaches:
(1) Look to see if a jQuery script was included: in contentScript.js
:
if ( document.querySelector('script[src*="jquery"]') ) {
// probably has jquery
}
(2) Look to see if jQuery
is defined: in contentScript.js
:
window.addEventListener('jQueryFound',function() {
// probably has jquery
});
var scriptTag = document.createElement('script');
scriptTag.textContent
= "if ( window.jQuery ) { window.dispatchEvent(new Event('jQueryFound')); }"
document.head.appendChild(scriptTag);
(1) will fail if the site author is using bad filenames. (2) will fail if they’ve redefined window.jQuery
(or if I messed up my javascript events api, since I’m not the best at javascript).
You could also simplify the above by including jQuery as a content script before you detect if jQuery is included. ;)
I ended up listening for "DOMContentLoaded" and then perform required actions.
Thanks for all input
There seems to be a similar stack overflow issue here for the web at large that I think will also apply to your extension: Trying to fire the onload event on script tag
It seems that you can set the src and onload elements of a script to get an event when the script loads.