简体   繁体   中英

Include library from CDN and local browsing

If loading jQuery from CDN with ...

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

... then it will not be accepted if the website is HTTPS ( Blocked loading mixed active content "http://ajax.googleapis.com/ajax/... ).


The solution seems to be :

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

Indeeed it will work if the website is HTTP or HTTPS. But when working on the file locally (ie browse the file on my hard drive), then jQuery is not loaded with this solution.


This is important for me, that people who will download my GitHub project will be able to test it locally.

How to include jQuery properly with CDN, and be able to browse locally the HTML file?

In general, testing web pages using file:// URLs is a bad idea and I wouldn't bother to support it. Instead, testing with a local webserver makes more sense.

But if you're intent on supporting it, you'll need to do a check on 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>

Or if you're doing an XHTML page (or just don't like 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>

That uses the protocol of the page ( http: , https: , whatever) if it's not file: , and uses http: if it's file: .

I tried with HTTPS all the time :

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

It seems to work :

  1. from local browsing of the HTML page ( file:// )

  2. from http browsing of the HTML page

  3. from https browsing of the HTML page

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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