I do not understand how the built-in script gets the variables from the window, that is, I wanted to do this:

<script src="script.js">var A = 123;</script> 

meanwhile, script.js gets the variable A:

 alert(A); 

But that doesn't work. An interesting option is not to write the full script inside the script tag, but only to transfer the necessary variables with which the script can work.

  • one
    If src is specified, aren't the instructions inside the script ignored? - Jean-Claude
  • @ Jean-Claude I do not know, have never been interested in this. - Shevsky
  • @NikolaTesla now look. - Shevsky pm
  • @NikolaTesla it, thanks - Shevsky

3 answers 3

I probably would have wrapped it all the same in anonymous functions, and exported the variable to a global object, so it would be more correct in my opinion, since in any case, writing a script or library in the global scope is not comme il faut.

 <script type="text/javascript"> (function(exports){ exports.a = 3; })(window); </script> <script type="text/javascript"> (function(exports){ console.log(exports.a); })(window); </script> 

    If the src parameter is specified, the contents of the <script> will be ignored.

     <script src="script.js">alert('Не будет выведено');</script> 

      You can like this

       <script>var A = 1;</script> <script src="script.js"></script> 

      And inside script.js, access global variable A.

      But of course, if there is no other way or the project is very simple.