I am writing a JS file that will be included as an external script in other pages using the HTML <script>
tag.
I want to make certain parts of the script optionally configurable by setting certain global variables. For example, imagine a script like this:
//external.js
var show = false;
$(function() {
if(show) alert('show');
else alert('no show');
});
//test.html
<script src="external.js"></script>
<script>show = true</script>
So I define the variable and its default value in the external script, but then overwrite it in the HTML file before displaying the alert on document ready.
Now this works fine so far, however it falls apart once I try to load external.js asynchronously using the async
attribute. This is because now the external script may actually become loaded after the show = true
line, meaning it will overwrite the custom value again with the default.
My current solution to this is something like this, which works but seems unnecessarily complicated:
//external.js
var show = false;
$(function() {
if ( typeof my_init == 'function' ) { my_init(); }
if(show) alert('show');
else alert('no show');
});
//test.html
<script async src="external.js"></script>
<script>function my_init() { show = true }</script>
Is there a better way to do things?