Alex
Alex

Reputation: 68470

How to get a list of loaded scripts, including the ones dynamically loaded

I'm trying to match a certain script with the currently loaded scripts on the page:

if($('script[src="' + sn + '"]').length == 0)
  $('head').append('<scr' + 'ipt src="' + sn +'"></scr' + 'ipt>');  

This works but only for scripts that were loaded normally.

For scripts that were injected using javascript, like the one in my condition, it doesn't work :(

Apparently scripts that are loaded this way are somehow invisible in the DOM, even though they run.

Upvotes: 2

Views: 5017

Answers (5)

Denis Vasenkov
Denis Vasenkov

Reputation: 1

You can check array of entries

const entries = performance.getEntries();

This entry includes properties

// entries[0];

{
  detail: null,
  duration: 1586,
  entryType: "measure",
  name: "Next.js-before-hydration",
  startTime: 0
}

Upvotes: 0

Jan Heil
Jan Heil

Reputation: 415

Hey you can use the PerformanceAPI:

https://developer.mozilla.org/en-US/docs/Web/API/Performance/getEntries

Upvotes: 0

noob
noob

Reputation: 9202

var isThere = false;
$("script").each(function() {
    if ($(this).attr("src") == sn) {
        isThere = true;  
        // this works also with injected scripts!!
    }
});
if (isThere === false) {
    $('head').append('<scr' + 'ipt src="' + sn +'"></scr' + 'ipt>');
}

Upvotes: 4

RobG
RobG

Reputation: 147383

It is impossible to know reliably what script elements have been loaded because once a script element is loaded and executed, it can be removed with zero effect on the document. Also, script elements inserted usig the innerHTML property don't get executed, so their presence is meaningless (more or less).

All you can do is get a list of the current script elements in the document, you can't reliably know which ones have been loaded or even executed.

Upvotes: 2

jfriend00
jfriend00

Reputation: 707318

Why don't you test for the existence of something in your script (such as a global variable name, a global object or a function name).

if (!window.functionName) {
    // script holding functionName must not be present so load it dynamically
}

Upvotes: 1

Related Questions