0

Is there a way to ensure a javascript file loads just once when reloading an HTML file (which references this javascript file)?

e.g.:

<script src="js/myscript.js" type="text/javascript"></script>

I would like this command to be something like:

<script src="js/myscript.js" type="text/javascript" opt="include_once"></script>

something like the PHP command include_once()...

... Is there a native way to do this (through the native script tag)? Or is it possible only with third-party libraries, like jQuery?

Thank you!

2
  • are you attempting to handle the case where someone may link in your script on the page twice? Commented Jun 5, 2013 at 18:51
  • if you reload the HTML, all the script contents of a hard-linked script tag will be discarded, so you would need to load it twice if you wanted to use it the second time... Commented Jun 5, 2013 at 19:21

1 Answer 1

1

Is there a native way to do this (through the native script tag)?

No. Browsers handle the caching usually and don't download the script twice. But they will execute it twice. So you either have to alter your script to bail when it encounters a pre existing instance of itself OR you could use a script loader and set some values to not load it again.

here's a popular namespace method, inside js/myscript.js:

var customApp = customApp || {
    // do your stuff here and if customApp already existed it will just skip this part
};
Sign up to request clarification or add additional context in comments.

Comments

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.