0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Martin Nilsson
  • 659
  • 1
  • 8
  • 17

3 Answers3

0

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. ;)

Teepeemm
  • 4,331
  • 5
  • 35
  • 58
0

I ended up listening for "DOMContentLoaded" and then perform required actions.

Thanks for all input

Martin Nilsson
  • 659
  • 1
  • 8
  • 17
  • 1
    This will tell you when the page has finished loading. But determining whether a specific script is present is a separate and more challenging problem. – Teepeemm Aug 31 '14 at 00:57
-1

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.

Community
  • 1
  • 1
petewil-G
  • 99
  • 4