简体   繁体   English

HTML如何加载外部JS文件

[英]How does HTML load external JS files

I'm a beginner in web dev and I've recently come across some code that includes two external JS files in the following way: 我是Web开发人员的初学者,最近以以下方式遇到了一些包含两个外部JS文件的代码:

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>

I know the browser will perform additional HTTP-requests to get the referenced files. 我知道浏览器将执行其他HTTP请求以获取引用的文件。 Now, this is what's got me wondering: 现在,这让我感到奇怪:

When I put the containing HTML-file into the XAMPP htdocs folder and access it via localhost, everything works fine. 当我将包含HTML的文件放入XAMPP htdocs文件夹并通过localhost访问它时,一切正常。 However, when I just open the local .html-file in Chrome oder Firefox, it won't be able to find these external JavaScripts. 但是,当我仅在Firefox或Chrome浏览器中打开本地.html文件时,它将无法找到这些外部JavaScript。

Obviously, this isn't a problem, since you wouldn't normally use an HTML-file that way, but I still wonder what happens here. 显然,这不是问题,因为您通常不会那样使用HTML文件,但是我仍然想知道这里会发生什么。 Does it need some kind of server to include external JS files? 是否需要某种服务器来包含外部JS文件? Interestingly, it works when I include the files like this: 有趣的是,当我包含以下文件时,它可以工作:

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

It would be really interesting to know why =) 知道为什么==真的很有趣

Cheers! 干杯!

本地主机具有http://协议,如果您将本地主机的url复制并粘贴到任何编辑器中,则您可以简单地看到带有本地主机url的http:// ,但是当您通过file://直接打开文件时,它没有,这就是为什么通过XAMPP本地主机访问时,文件已加载。

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script> is using a relative url, it will use the protocol scheme from the displayed page, but against the host in the URL. <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>使用的是相对网址,它将使用显示页面中的协议方案,但要针对其中的主机网址。 On an HTTPS page, this will be an HTTPS request, on an HTTP page, it will be an HTTP request. 在HTTPS页面上,这将是一个HTTPS请求,在HTTP页面上,这将是一个HTTP请求。

So in other words it will look for the correct protocol - HTTP or HTTPS - used by the requested page and use that. 因此,换句话说,它将查找并使用请求的页面使用的正确协议-HTTP或HTTPS。

Here is a good read about this topic: http://nedbatchelder.com/blog/200710/httphttps_transitions_and_relative_urls.html 这是有关此主题的好书: http : //nedbatchelder.com/blog/200710/httphttps_transitions_and_relative_urls.html

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

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