简体   繁体   English

一个javascript文件可以被多个html文件使用吗?

[英]Can a single javascript file be used by multiple html files?

I have a javascript file main.js and five html files 1.html,2.html,3.html,4.html,5.html I want to access the javascript file main.as in all files .我有一个 javascript 文件 main.js 和五个 html 文件 1.html,2.html,3.html,4.html,5.html 我想访问所有文件中的 javascript 文件 main.as 。 I have used in all of the five but I'm not able to access it .我已经使用了所有五个,但我无法访问它。 Is it possible to share the .js file among the html files.是否可以在 html 文件之间共享 .js 文件。

Plz reply,请回复,

Thanks in advance提前致谢

Prashant Dubey普拉尚·杜比

Yes, it is entirely possible.是的,这是完全可能的。 That's the point of being able to have a JS file instead of having to embed all the code in the HTML.这就是能够拥有一个 JS 文件而不必将所有代码嵌入 HTML 中的意义所在。

yes this is well possible.是的,这很有可能。 You merely have to include你只需要包括

<script type="text/javascript" src="main.js"></script>

in your HTML files, preferably near the bottom (for faster rendering).在你的 HTML 文件中,最好靠近底部(为了更快的渲染)。 What have you done so far?到目前为止你做了什么?

Yes.是的。 Totally possible.完全有可能。

Just reference it in all of the files eg by只需在所有文件中引用它,例如

<script type="text/javascript" src="Scripts/main.js"></script>

Yes, it is possible.对的,这是可能的。

Probably there is something wrong with the way you access the javascript from your html.您从 html 访问 javascript 的方式可能有问题。 Show us the <script ...>...</script> part of your html.向我们展示您的 html 的<script ...>...</script>部分。

Yes.是的。 Are you using the correct path to the main.js file in your html files?您是否在 html 文件中使用了正确的 main.js 文件路径?

It can happen both ways..它可以发生两种方式..

  1. a single html file can use multiple javascript file一个 html 文件可以使用多个 javascript 文件

2.a javascript file can be used in several html files. 2.一个javascript文件可以在多个html文件中使用。

In first case javascript file load can be conditional based on location, user preferences, time, age group, content restriction.在第一种情况下,javascript 文件加载可以基于位置、用户偏好、时间、年龄组、内容限制。 You can see good example when facebook loads its page.当 facebook 加载其页面时,您可以看到很好的例子。 I loads number of javascritps.我加载了一些 javascritps。

Create separate javascript file with .js extension with all your function in it and just include this javascript file in the head tag of all the html scripts u wanna use that in.使用.js扩展名创建单独的 javascript 文件,其中包含您的所有功能,并将此 javascript 文件包含在您要使用的所有 html 脚本的 head 标记中。

Like::喜欢::

<html>
<head>
<script type="text/javascript" src="JavaScriptFilePath.js"></script>
</head>
<body>
<!-- use javascript -->

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

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