admin管理员组

文章数量:1319017

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.

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.

Share Improve this question asked Nov 14, 2011 at 2:02 AlexAlex 68.1k185 gold badges459 silver badges650 bronze badges 2
  • How were the scripts dynamically loaded? – Ry- Commented Nov 14, 2011 at 2:05
  • like I wrote above, with append('... – Alex Commented Nov 14, 2011 at 2:06
Add a ment  | 

5 Answers 5

Reset to default 4
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>');
}

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.

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
}

Hey you can use the PerformanceAPI:

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

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
}

本文标签: