When you first write a new JavaScript the easiest way to set it up is to embed the JavaScript code directly into the web page so that everything is in the one place while you test it to get it working right. Similarly, if you are inserting a pre-written script into your website the instructions may tell you to embed parts or all of the script into the web page itself.
首次编写新JavaScript时,最简单的设置方法是将JavaScript代码直接嵌入到网页中,以便在测试使其正常工作的同时将所有内容都放在一个位置。 同样,如果您要在网站中插入预先编写的脚本,则说明可能会告诉您将部分或全部脚本嵌入到网页本身中。
This is okay for setting up the page and getting it to work properly in the first place but once your page is working the way that you want it you will be able to improve the page by extracting the JavaScript into an external file so that your page content in the HTML isn't so cluttered with non-content items such as JavaScript.
可以首先设置页面并使它正常运行,但是一旦页面按照您希望的方式工作,您就可以通过将JavaScript提取到外部文件中来改进页面,以便页面HTML中的内容不会被非内容项(例如JavaScript)弄得很杂乱。
If you just copy and use JavaScripts written by other people then their instructions on how to add their script to your page may have resulted in your having one or more large sections of JavaScript actually embedded into your web page itself and their instructions don't tell you how you can move this code out of your page into a separate file and still have the JavaScript work. Don't worry though because regardless of what code the JavaScript you are using in your page you can easily move the JavaScript out of your page and set it up as a separate file (or files if you have more than one piece of JavaScript embedded in the page). The process for doing this is always the same and is best illustrated with an example.
如果您只是复制和使用其他人编写JavaScript,那么他们关于如何将其脚本添加到页面的说明可能会导致您将一个或多个JavaScript实际嵌入到您的网页本身中,而他们的说明却没有告诉您您如何将这段代码从页面移出到一个单独的文件中,并且仍然可以使用JavaScript。 不过请不要担心,因为无论页面中使用的是什么代码,您都可以轻松地将JavaScript移出页面并将其设置为单独的文件(或者如果您嵌入了多个JavaScript的文件,则可以将其设置为一个文件)这一页)。 这样做的过程始终是相同的,并通过一个示例来最好地说明。
Let's look at how a piece of JavaScript might look when embedded in your page. Your actual JavaScript code will be different from that shown in the following examples but the process is the same in every case.
让我们看一下嵌入页面中的一段JavaScript的外观。 您的实际JavaScript代码将与以下示例中显示的代码不同,但是每种情况下的处理过程都是相同的。
例子一 ( Example One )
<script type="text/javascript">if (top.location != self.location)
top.location = self.location;
</script>
例子二 ( Example Two )
<script type="text/javascript"><!--if (top.location != self.location)
top.location = self.location;
// -->
</script>
例三 ( Example Three )
<script type="text/javascript">
/* <![CDATA[ */if (top.location != self.location)
top.location = self.location;
/* ]]> */
</script>
Your embedded JavaScript should look something like one of the above three examples. Of course, your actual JavaScript code will be different from that shown but the JavaScript will probably be embedded into the page using one of the above three methods. In some cases, your code may use the outdated language="javascript" instead of type="text/javascript" in which case you may want to bring your code more up to date to start with by replacing the language attribute with the type one.
您的嵌入式JavaScript应该类似于以上三个示例之一。 当然,您实际JavaScript代码将与显示的代码不同,但是JavaScript可能会使用上述三种方法之一嵌入到页面中。 在某些情况下,您的代码可能会使用过时的language =“ javascript”而不是type =“ text / javascript”,在这种情况下,您可能希望通过将语言属性替换为类型一来使代码更新为最新版本。
Before you can extract the JavaScript into its own file you first need to identify the code to be extracted. In all three of the above examples, there are two lines of actual JavaScript code to be extracted. Your script will probably have a lot more lines but can be readily identified because it will occupy the same place within your page as the two lines of JavaScript that we have highlighted in the above three examples (all three of the examples contain the same two lines of JavaScript, it is just the container around them that is slightly different).
在将JavaScript提取到其自己的文件中之前,首先需要确定要提取的代码。 在以上所有三个示例中,有两行实际JavaScript代码要提取。 您的脚本可能会有更多行,但是很容易识别,因为它在页面中的位置与我们在上面三个示例中突出显示JavaScript的两行相同(所有三个示例都包含相同的两行) JavaScript,只是它们周围的容器略有不同)。
- The first thing you need to do to actually extract the JavaScript into a separate file is to open a plain text editor and access the content of your web page. You then need to locate the embedded JavaScript that will be surrounded by one of the variations of code shown in the above examples. 将JavaScript实际提取到单独文件中所需要做的第一件事是打开纯文本编辑器并访问网页的内容。 然后,您需要找到将被上述示例中显示的代码变体之一包围的嵌入式JavaScript。
- Having located the JavaScript code you need to select it and copy it to your clipboard. With the above example, the code to be selected is highlighted, you do not need to select the script tags or the optional comments that may appear around your JavaScript code. 找到JavaScript代码后,您需要选择它并将其复制到剪贴板。 在上面的示例中,将突出显示要选择的代码,您无需选择脚本标签或JavaScript代码周围可能出现的可选注释。
- Open another copy of your plain text editor (or another tab if your editor supports opening more than one file at a time) and past the JavaScript content there. 打开您的纯文本编辑器的另一个副本(如果您的编辑器一次支持打开多个文件,则打开另一个选项卡),然后将JavaScript内容粘贴在那里。
Select a descriptive filename to use for your new file and save the new content using that filename. With the example code, the purpose of the script is to break out of frames so an appropriate name could be framebreak.js.
选择用于新文件的描述性文件名,并使用该文件名保存新内容。 使用示例代码,脚本的目的是打破框架,因此合适的名称可以是framebreak.js 。
- So now we have the JavaScript in a separate file we return to the editor where we have the original page content to make the changes there to link to the external copy of the script. 因此,现在我们将JavaScript放在一个单独的文件中,返回到编辑器,在编辑器中,我们拥有原始页面内容,可以在那里进行更改以链接到脚本的外部副本。
- As we now have the script in a separate file we can remove everything between the script tags in our original content so that the </script&;script tag immediately follows the <script type="text/javascript"> tag. 由于我们现在将脚本保存在单独的文件中,因此我们可以删除原始内容中script标记之间的所有内容,以便</ script&; script标记紧随<script type =“ text / javascript”>标记之后。
The final step is to add an extra attribute to the script tag identifying where it can find the external JavaScript. We do this using a src="filename" attribute. With our example script, we would specify src="framebreak.js".
最后一步是向脚本标签添加额外的属性,以标识可以在哪里找到外部JavaScript。 我们使用src =“ filename”属性执行此操作。 在示例脚本中,我们将指定src =“ framebreak.js”。
The only complication to this is if we have decided to store the external JavaScripts in a separate folder from the web pages that use them. If you do this then you need to add the path from the web page folder to the JavaScript folder in front of the filename. For example, if the JavaScripts are being stored in a js folder within the folder that holds our web pages we would need src="js/framebreak.js"
唯一的麻烦是,如果我们决定将外部JavaScript存储在与使用它们的网页不同的文件夹中。 如果这样做,则需要将网页文件夹的路径添加到文件名前面JavaScript文件夹。 例如,如果将JavaScript存储在保存我们网页的文件夹中的js文件夹中,则需要src =“ js / framebreak.js”
So what does our code look like after we have separated the JavaScript out into a separate file? In the case of our example JavaScript (assuming that the JavaScript and HTML are in the same folder) our HTML in the web page now reads:
那么,在将JavaScript分离到一个单独的文件中之后,我们的代码是什么样的呢? 对于我们的示例JavaScript(假设JavaScript和HTML在同一个文件夹中),网页中HTML现在显示为:
<script type="text/javascript" src="framebreak.js"> </script>
We also have a separate file called framebreak.js that contains:
我们还有一个名为framebreak.js的单独文件,其中包含:
if (top.location != self.location) top.location = self.location;
Your filename and file content will be a lot different from that because you will have extracted whatever JavaScript was embedded in your web page and given the file a descriptive name based on what it does. The actual process of extracting it will be the same though regardless of what lines it contains.
您的文件名和文件内容将与之大不相同,因为您将提取网页中嵌入的所有JavaScript,然后根据文件的名称为文件指定一个描述性名称。 无论它包含什么行,提取它的实际过程都是相同的。
What about those other two lines in each of examples two and three? Well, the purpose of those lines in example two is to hide the JavaScript from Netscape 1 and Internet Explorer 2, neither of which anyone uses any more and so those lines are not really needed in the first place. Placing the code in an external file hides the code from browsers that don't understand the script tag more effectively than surrounding it in an HTML comment anyway. The third example is used for XHTML pages to tell validators that the JavaScript should be treated as page content and not to validate it as HTML (if you are using an HTML doctype rather than an XHTML one then the validator already knows this and so those tags are not needed). With the JavaScript in a separate file there is no longer any JavaScript in the page to be skipped over by validators and so those lines are no longer needed.
例二和例三的其他两行呢? 好吧,示例二中这些行的目的是在Netscape 1和Internet Explorer 2中隐藏JavaScript,而这两个人都不再使用它们,因此,实际上并不需要这些行。 将代码放置在外部文件中会对无法理解脚本标签的浏览器隐藏代码,而不是将脚本标签始终包围在HTML注释中。 第三个示例用于XHTML页面,以告知验证者将JavaScript视为页面内容,而不是将其验证为HTML(如果您使用的是HTML doctype而不是XHTML,则验证器已经知道这一点,因此这些标记不需要)。 将JavaScript放在单独的文件中,验证器将不再跳过页面中的任何JavaScript,因此不再需要这些行。
One of the most useful ways that JavaScript can be used to add functionality to a web page is to perform some sort of processing in response to an action by your visitor. The most common action that you want to respond to will be when that visitor clicks on something. The event handler that allows you to respond to visitors clicking on something is called onclick.
可以使用JavaScript向网页添加功能的最有用的方法之一是响应访问者的操作执行某种处理。 您要响应的最常见操作是该访客单击某物时。 允许您响应访问者单击某些事件的事件处理程序称为onclick 。
When most people first think about adding an onclick event handler to their web page they immediately think of adding it to an <a> tag. This gives a piece of code that often looks like:
当大多数人第一次考虑将onclick事件处理程序添加到其网页时,他们立即想到将其添加到<a>标记中。 这给出了一段通常看起来像这样的代码:
<a href="#" onclick="dosomething(); return false;">
This is the wrong way to use onclick unless you have an actual meaningful address in the href attribute so that those without JavaScript will be transferred somewhere when they click on the link. A lot of people also leave out the "return false" from this code and then wonder why the top of the current page always gets loaded after the script has run (which is what the href="#" is telling the page to do unless false is returned from all the event handlers. Of course, if you have something meaningful as the destination of the link then you may want to go there after running the onclick code and then you will not need the "return false".
除非您在href属性中有一个实际有意义的地址,否则那些使用onclick的方法是错误的 ,这样,那些没有JavaScript的用户在单击链接时将被转移到某个地方。 很多人还忽略了这段代码中的“ return false”,然后想知道为什么脚本运行后总是总是加载当前页面的顶部(这就是href =“#”告诉页面执行的操作,除非从所有事件处理程序返回false,当然,如果您将有意义的内容用作链接的目标,则可能需要在运行onclick代码之后转到那里,然后就不需要“ return false”。
What many people do not realize is that the onclick event handler can be added to any HTML tag in the web page in order to interact when your visitor clicks on that content. So if you want something to run when people click on an image you can use:
许多人没有意识到,可以将onclick事件处理程序添加到网页中的任何 HTML标记中,以便在访问者单击该内容时进行交互。 因此,如果您希望人们在单击图像时运行某些内容,则可以使用:
<img src="myimg.gif" onclick="dosomething()">
If you want to run something when people click on some text you can use:
如果要在人们单击某些文本时运行某些内容,可以使用:
<span onclick="dosomething()">some text</span>
Of course, these don't give the automatic visual clue that there will be a response if your visitor clicks on them the way that a link does but you can add that visual clue easily enough yourself by styling the image or span appropriately.
当然,如果访问者按链接的方式单击它们,它们不会自动给出视觉提示,但是您可以通过适当设置图像的样式或跨度来轻松地添加视觉提示。
The other thing to note about these ways of attaching the onclick event handler is that they do not require the "return false" because there is no default action that will happen when the element is clicked on that needs to be disabled.
关于附加onclick事件处理程序的这些方式的另一点要注意的是,它们不需要“ return false”,因为在元素上单击时没有默认动作将被禁用,因此无需禁用它。
These ways of attaching the onclick are a big improvement on the poor method that many people use but it is still a long way from being the best way of coding it. One problem with adding onclick using any of the above methods is that it is still mixing your JavaScript in with your HTML. onclick is not an HTML attribute, it is a JavaScript event handler. As such to separate our JavaScript from our HTML to make the page easier to maintain we need to get that onclick reference out of the HTML file into a separate JavaScript file where it belongs.
这些附加onclick的方法是对许多人使用的较差方法的一项重大改进,但距离成为对其进行编码的最佳方法还有很长的路要走。 使用上述任何一种方法添加onclick的一个问题是,它仍会将JavaScript与HTML混合在一起。 onclick 不是 HTML属性,而是JavaScript事件处理程序。 因此,要将我们JavaScript与HTML分开以使页面易于维护,我们需要将onclick引用从HTML文件中获取到属于它的单独JavaScript文件中。
The easiest way to do this is to replace the onclick in the HTML with an id that will make it easy to attach the event handler to the appropriate spot in the HTML. So our HTML might now contain one of these statements:
最简单的方法是将HTML中的onclick替换为一个ID ,该ID将使事件处理程序易于附加到HTML中的适当位置。 因此,我们HTML现在可能包含以下语句之一:
< img src="myimg.gif" id="img1"> <span id="sp1">some text</span>
We can then code the JavaScript in a separate JavaScript file that is either linked into the bottom of the body of the page or which is in the head of the page and where our code is inside a function that is itself called after the page finishes loading. Our JavaScript to attach the event handlers now looks like this:
然后,我们可以将JavaScript编码在一个单独JavaScript文件中,该文件可以链接到页面主体的底部,也可以链接到页面的顶部,并且我们的代码位于该函数内部,该函数在页面加载完成后即被调用。 现在,用于附加事件处理程序JavaScript如下所示:
document.getElementById('img1').onclick = dosomething; document.getElementById('sp1').onclick = dosomething;
One thing to note. You will notice that we have always written onclick entirely in lowercase. When coding the statement in their HTML you will see some people write it as onClick. This is wrong as the JavaScript event handlers names are all lowercase and there is no such handler as onClick. You can get away with it when you include the JavaScript inside your HTML tag directly since HTML is not case sensitive and the browser will map it across to the correct name for you. You can't get away with the wrong capitalization in your JavaScript itself since the JavaScript is case sensitive and there is no such thing in JavaScript as onClick.
需要注意的一件事。 您会注意到,我们始终将onclick完全写成小写。 在用HTML编码语句时,您会看到有些人将其写为onClick。 这是错误的,因为JavaScript事件处理程序的名称都是小写,并且没有onClick这样的处理程序。 当您直接在HTML标记中包含JavaScript时,就可以避免使用它,因为HTML不区分大小写,并且浏览器会为您映射正确的名称。 您无法避免JavaScript本身的大小写错误,因为JavaScript区分大小写,并且JavaScript中没有onClick之类的东西。
This code is a huge improvement over the prior versions because we are now both attaching the event to the correct element within our HTML and we have the JavaScript completely separate from the HTML. We can improve on this even further though.
此代码是对先前版本的巨大改进,因为我们现在都将事件附加到HTML中的正确元素上,并且JavaScript与HTML完全分开。 但是,我们可以进一步改进。
The one problem that is remaining is that we can only attach one onclick event handler to a specific element. Should we at any time need to attach a different onclick event handler to the same element then the previously attached processing will no longer be attached to that element. When you are adding a variety of different scripts to your web page for different purposes there is at least a possibility that two or more of them may want to provide some processing to be performed when the same element is clicked on. The messy solution to this problem is to identify where this situation arises and to combine the processing that needs to be called together to a function that performs all of the processing.
剩下的一个问题是,我们只能将一个onclick事件处理程序附加到特定元素。 如果我们随时需要将不同的onclick事件处理程序附加到同一元素,则以前附加的处理将不再附加到该元素。 当您出于各种目的将各种不同的脚本添加到您的网页时,至少有一种可能是其中两个或多个脚本可能希望提供一些在单击同一元素时要执行的处理。 解决该问题的麻烦方法是确定这种情况的发生位置,并将需要调用的处理与执行所有处理的功能结合在一起。
While clashes like this are less common with onclick than they are with onload, having to identify the clashes in advance and combine them together is not the ideal solution. It is not a solution at all when the actual processing that needs to be attached to the element changes over time so that sometimes there is one thing to do, sometimes another, and sometimes both.
尽管此类冲突在onclick上比在onload上少见,但必须提前识别这些冲突并将其组合在一起并不是理想的解决方案。 当需要附加到元素上的实际处理过程随时间变化时,有时要做一件事,有时又要做另一件事,有时两者兼而有之,这根本不是解决方案。
The best solution is to stop using an event handler completely and to instead use a JavaScript event listener (along with the corresponding attachEvent for Jscript- since this is one of those situations where JavaScript and JScript differ). We can do this most easily by first creating an addEvent function that will add either an event listener or attachment depending on which of the two that the language being run supports;
最好的解决方案是完全停止使用事件处理程序,而改为使用JavaScript事件侦听器(以及与Jscript对应的attachEvent,因为这是JavaScript和JScript不同的情况之一)。 我们可以通过首先创建一个addEvent函数来最轻松地做到这一点,该函数将添加事件侦听器或附件,具体取决于运行的语言所支持的是哪一种;
function addEvent(el, eType, fn, uC) { if (el.addEventListener) { el.addEventListener(eType, fn, uC); return true; } else if (el.attachEvent) { return el.attachEvent('on' + eType, fn); } }
We can now attach the processing that we want to have happen when our element is clicked on using:
现在,当使用元素单击元素时,我们可以附加希望发生的处理:
addEvent( document.getElementById('spn1'), 'click',dosomething,false);
Using this method of attaching the code to be processed when an element is clicked on means that making another addEvent call to add another function to be run when a specific element is clicked on will not replace the prior processing with the new processing but will instead allow both of the functions to be run. We have no need to know when calling an addEvent whether or not we already have a function attached to the element to run when it is clicked on, the new function will be run along with and functions that were previously attached.
使用这种在单击元素时附加要处理的代码的方法,意味着在单击特定元素时进行另一个addEvent调用以添加要运行的另一个函数不会用新的处理替换先前的处理,而是允许这两个要运行的功能。 我们不需要在调用addEvent时就知道是否已经有一个附加到元素上的函数可以在单击该元素时运行,新函数将与和先前附加的函数一起运行。
Should we need the ability to remove functions from what gets run when an element is clicked on then we could create a corresponding deleteEvent function that calls the appropriate function for removing an event listener or attached event?
我们是否应该具有从单击元素时运行的功能中删除功能的能力,然后我们可以创建一个相应的deleteEvent函数,该函数调用相应的函数来删除事件侦听器或附加事件?
The one disadvantage of this last way of attaching the processing is those really old browsers do not support these relatively new ways of attaching event processing to a web page. There should be few enough people using such antiquated browsers by now to disregard them in what J(ava)Script we write apart from writing our code in such a way that it doesn't cause huge numbers of error messages. The above function is written so as to do nothing if neither of the ways it uses is supported. Most of these really old browsers do not support the getElementById method of referencing HTML either and so a simple if (!document.getElementById) return false; at the top of any of your functions which do such calls would also be appropriate. Of course, many people writing JavaScript are not so considerate of those still using antique browsers and so those users must be getting used to seeing JavaScript errors on almost every web page they visit by now.
最后一种附加处理的方式的缺点是那些真正的旧浏览器不支持将事件处理附加到网页的这些较新的方式。 到现在为止,应该只有很少的人使用这种过时的浏览器来忽略我们编写的J(ava)Script,而不会以不会引起大量错误消息的方式编写代码。 如果以上两种功能均不受支持,则编写上述功能以使其不执行任何操作。 大多数这些真正古老的浏览器也不支持引用HTML的getElementById方法,因此简单的if(!document.getElementById)返回false。 在执行此类调用的任何函数的顶部也将是适当的。 当然,许多编写JavaScript的人并不太考虑那些仍在使用旧版浏览器的人,因此,这些用户必须习惯于看到他们现在访问的几乎每个网页上JavaScript错误。
Which of these different ways do you use to attach processing into your page to be run when your visitors click on something? If the way you do it is nearer to the examples at the top of the page than to those examples at the bottom of the page then perhaps it is time you thought about improving the way you write your onclick processing to use one of the better methods presented lower down on the page.
当访问者单击某些内容时,您使用以下哪种不同的方式将处理附加到页面中以便运行? 如果您的方法比页面底部的示例更接近页面顶部的示例,那么可能是时候考虑考虑改进编写onclick处理的方法以使用更好的方法之一了在页面下方显示。
Looking at the code for the cross-browser event listener you will notice that there is a fourth parameter which we called uC, the use of which isn't obvious from the prior description.
查看跨浏览器事件侦听器的代码,您会注意到有一个名为uC的第四个参数,根据先前的描述,该参数的使用并不明显。
Browsers have two different orders in which they can process events when the event is triggered. They can work from the outside inwards from the <body> tag in towards the tag that triggered the event or they can work from the inside out starting at the most specific tag. These two are called capture and bubble respectively and most browsers allow you to choose which order multiple processing should be run in by setting this extra parameter.
浏览器具有两种不同的顺序,当事件被触发时,浏览器可以处理事件。 他们可以从<body>标记从外部向内朝着触发事件的标记进行工作,也可以从最具体的标记开始由内而外进行工作。 这两个分别称为捕获和冒泡 ,大多数浏览器允许您通过设置此额外参数来选择执行多个处理的顺序。
- uC = true to process during the capture phase uC = true,在捕获阶段进行处理
- uC = false to process during the bubble phase. uC = false,在冒泡阶段处理。
So where there are several other tags wrapped around the one that the event was triggered on the capture phase runs first starting with the outermost tag and moving in toward the one that triggered the event and then once the tag the event was attached to has been processed the bubble phase reverses the process and goes back out again.
因此,在捕获阶段触发事件的标记周围还包裹着其他几个标记,首先从最外面的标记开始运行,然后移向触发事件的标记,然后将事件附加到的标记处理完毕气泡阶段将逆转该过程,然后再次退出。
Internet Explorer and traditional event handlers always process the bubble phase and never the capture phase and so always start with the most specific tag and work outwards.
Internet Explorer和传统事件处理程序始终处理冒泡阶段,而不处理捕获阶段,因此始终从最具体的标记开始并向外进行工作。
So with event handlers:
因此,使用事件处理程序:
<div onclick="alert('a')><div onclick="alert('b')">xx</div></div>
clicking on the xx would bubble out triggering the alert('b') first and the alert('a') second.
单击xx会冒出气泡,首先触发警报(b),然后触发警报(a)。
If those alerts were attached using event listeners with uC true then all modern browsers except Internet Explorer would process the alert('a') first and then the alert('b').
如果使用uC为true的事件侦听器附加了这些警报,则除Internet Explorer以外的所有现代浏览器都会先处理警报('a'),然后再处理警报('b')。
翻译自: https://www.thoughtco.com/moving-javascript-out-of-the-web-page-2037542