1

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 = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(s);

What is the best way to achieve this?

thanks

0

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

7 Comments

I'll need a lot more information to understand how your code is set up.
Not quite good solution. If the util.js hasn't been downloaded, technically, it can be downloaded again by the other script.
The download will happen only if the utilLoaded switch is not set, or is false. Since this is immediately set to true at the time the external script element is created, it couldn't possibly be loaded again by the same page. A side note - this solution will work until the page is refreshed. For a persistent solution, you'll need a server-side variable (not in Javascript).
It is set only after utils.js was downloaded! it can take a few seconds, in which the other script can be loaded and read that var, which is not yet defined!
Well, then put it before the appendChild call, and it will be set before the util.js is appended.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.