繁体   English   中英

包括CDN中的库和本地浏览

[英]Include library from CDN and local browsing

如果从CDN加载jQuery与...

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/...

...则如果网站为HTTPS(被Blocked loading mixed active content "http://ajax.googleapis.com/ajax/... ),则该网站将被接受。


解决方案似乎是:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/...

实际上,如果网站是HTTP或HTTPS,它将正常工作。 但是,在本地处理文件时 (即浏览我的硬盘上的文件),则jQuery不会加载此解决方案。


这对我很重要,下载我的GitHub项目的人将能够在本地对其进行测试。

如何在CDN中正确包含jQuery,并能够在本地浏览HTML文件?

通常,使用file:// URL测试网页不是一个好主意,我也不会支持它。 相反,使用本地Web服务器进行测试更有意义。

但是,如果您打算支持它,则需要对location.protocol进行检查:

<script>
(function() {
    var protocol = location.protocol === "file:" ? "http:" : location.protocol;
    document.write('<script src="' + protocol + '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"><\/script>');
})();
</script>

或者,如果您正在处理XHTML页面(或者只是不喜欢document.write ):

<script>
(function() {
    var protocol = location.protocol === "file:" ? "http:" : location.protocol;
    var script = document.createElement('script');
    script.src = protocol + '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js';
    document.getElementsByTagName("script")[0].parentNode.appendChild(script);
})();
</script>

使用该页面的协议( http: https:什么的),如果它不是file: ,并使用http:如果是file:

我一直尝试使用HTTPS:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/...

似乎有效:

  1. 从HTML页面的本地浏览( file://

  2. 从http浏览HTML页面

  3. 通过https浏览HTML页面

在HTML5 Boilerplate中,在CDN脚本之后添加:

<script>window.jQuery || document.write('<script src="/path/to/local/jquery.js"><\/script>')</script>

暂无
暂无

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

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