user1695700
user1695700

Reputation: 71

Loading javascript file just once when reloading (native way)

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!

Upvotes: 0

Views: 341

Answers (1)

Anthony Hatzopoulos
Anthony Hatzopoulos

Reputation: 10557

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
};

Upvotes: 1

Related Questions