1

I have some inline JavaScript on several different pages like this:

$(function() {
   var myVar1 = ...;
   var myVar2 = ...;
   var myVar3 = ...;

   function myFunc1() {
      ...
   }

   function myFunc2() {
      ...
   }

   if (blah blah) {
      myFunc1();
   }
   else {
      myFunc2();
   }
});

I would like to move them into an external script, which is the recommended way of deploying client-side JavaScript.

However, for each individual page, I have a different value for variable myVar1, so it seems like I have to create multiple very similar JS files because of this tiny difference. Is there any better way?

1 Answer 1

2

You could store the variable in a relevant existing HTML element attribute, and retrieve it within the code:

<div class="myclass" data-var1="Page 1"></div>


$(function() {
   var myVar1 = $(".myclass").data("var1");
   var myVar2 = ...;
   var myVar3 = ...;

   function myFunc1() {
      ...
   }

   function myFunc2() {
      ...
   }

   if (blah blah) {
      myFunc1();
   }
   else {
      myFunc2();
   }
});

Another solution would be to take myVar1 out of your function and declare it as a global variable in each page.

For example:

<script type="text/javascript">
  var myVar1 = 'Page1';
</script>
<script type="text/javascript" src="myscript.js"></script>

For clarification, "myscript.js" would be:

$(function() {
   var myVar2 = ...;
   var myVar3 = ...;

   function myFunc1() {
      ...
   }

   function myFunc2() {
      ...
   }

   if (blah blah) {
      myFunc1();
   }
   else {
      myFunc2();
   }
});
Sign up to request clarification or add additional context in comments.

3 Comments

but that's gonna pollute the global variable space, which kinda defeats the purpose of making the closure?
@MLister I've edited my answer to provide an alternative solution if you do not wish to use global variables.
@MLister The purpose of your closure is to run after the DOM has loaded, as you are using shorthand jQuery $(document).ready(). But I appreciate global variables aren't always the neatest solution.

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.