Reputation: 68470
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
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
Reputation: 415
Hey you can use the PerformanceAPI:
https://developer.mozilla.org/en-US/docs/Web/API/Performance/getEntries
Upvotes: 0
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
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
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