开发者

How to load JS scripts that will add only one additional script

开发者 https://www.devze.com 2023-02-01 01:59 出处:网络
I have 2 script files that you put in the <head> However, they share the same Util script file. I want that in case they are both loaded on the same page, the util file will load only once.

I have 2 script files that you put in the <head>

However, they share the same Util script file. I want that in case they are both loaded on the same page, the util file will load only once.

If only one of them is loaded, the util will still be loaded once... I cant use <script src=...utils.js>... only the 2 scripts I am using

var s = document.createElement("script");
s.src = s3 + "/js_enc/utils.js";
s.type = "te开发者_Go百科xt/javascript";
document.getElementsByTagName("head")[0].appendChild(s);

What is the best way to achieve this?

thanks


This doesn't seem like a problem, since the Util script will only be loaded when it is declared:

<script type='text/javascript' src='util.js'></script>
<script type='text/javascript' src='script1.js'></script>
<script type='text/javascript' src='script2.js'></script>

But if you want to check that the script has been loaded, you could set a global variable in the Util script, something like

var utilFound = true;

Then check in each script to see if it is set or not.

if(!utilFound) { alert("Util not loaded!"); }

You could also toggle the variable depending on some condition, for example:

if(utilFound) { 
  alert("Util hasn't been accessed yet."); 
  utilFound = false;
}
else {
  alert("Util has already been accessed.");
}

UPDATE

As per your edit, the "check if set and toggle" solution would work fine. If the variable has been set, don't run your document.createElement code.

In your util.js file, add

var utilLoaded = false;

Then in each script, add your snippet, plus a utilLoaded check/toggle:

if(!utilLoaded) {
  var s = document.createElement("script");
  ....
  utilLoaded = true;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号