简体   繁体   English

HTML脚本标记和javascript文件通信

[英]HTML script tag and javascript file communication

I have a script tag in my HTML file 我的HTML文件中有一个脚本标记

<head>
<script src="myjs.js"></script>
<script> 
</script>
</head>

<body>
</body>

and a external javascript file , Is there a way the variables in the script tag interact with the script in the javascript file ? 和外部javascript文件,脚本标记中的变量是否有一种方式与javascript文件中的脚本交互?

Both the content of the script file and the following script element will be treated as global code as if they were in a single script element. 脚本文件的内容和以下脚本元素都将被视为全局代码,就好像它们位于单个脚本元素中一样。

However , code in the first file will be executed before the content of the second script element is parsed or executed (which means that variables declared and initialised in the second script don't exist for the first script). 但是 ,第一个文件中的代码将在解析或执行第二个脚本元素的内容之前执行(这意味着第一个脚本中不存在在第二个脚本中声明和初始化的变量)。

Absolutely. 绝对。 Once your external file is loaded into the page, it's treated as if it was coded in the page like your second script. 将外部文件加载到页面后,就会将其视为在页面中编码,就像第二个脚本一样。 Depending on how you've scoped your variables, there may be conflicts and values can be changed/overridden. 根据您对变量进行范围调整的方式,可能存在冲突,可以更改/覆盖值。

Your html structure seem invalid 你的html结构似乎无效

should be 应该

<html>
  <head>
    <script type="text/javascript" src="myjs.js"></script>
    <script type="text/javascript">

       //Now you can use external variable here

    </script>
  </head>
  <body>
  </body>
</html>

If you want to reference variables from the javascript file from code in the script tag, you need to make sure that the javascript file has been loaded. 如果要从脚本标记中的代码引用javascript文件中的变量,则需要确保已加载javascript文件。 The common way to do that is to attach a handler to the window.onload event and reference the variables from the file in that handler. 执行此操作的常用方法是将处理程序附加到window.onload事件,并从该处理程序中的文件引用变量。 The simplest (but not necessarily the best) way to do this is as follows: 最简单(但不一定是最好)的方法如下:

<script> 
  window.onload = function() {
      // reference loaded variables, domNodes, etc
  }
</script>

Most javascript libraries/frameworks have mechanisms for doing this. 大多数javascript库/框架都有执行此操作的机制。 See jQuery .ready() for an example of one. 有关一个示例,请参阅jQuery .ready()

If you have a large application that you would like to split into meaningful modules, I'd recommend investigating AMD (Asychronous Module Definition). 如果您想要将大型应用程序拆分为有意义的模块,我建议您调查AMD (异步模块定义)。 There is a nice set of slides describing what AMD is and why you would want to use it at http://blog.amt.in/asynchronous-module-definition-amd-why-what-a 有一套很好的幻灯片描述了AMD是什么以及为什么要在http://blog.amt.in/asynchronous-module-definition-amd-why-what-a上使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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