简体   繁体   中英

Migrating inline JavaScript to external files

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM