Is a URL starting with // valid?

2019-01-25 03:24发布

We can see many HTML page using src="//example.com/myjavascript.js" to include a .js and let the browser use http:// / https:// depending on the current scheme of the page URL.

Is this a valid URI ?

标签: url
3条回答
成全新的幸福
2楼-- · 2019-01-25 04:00

Yes, it is definitely valid. It is a "scheme relative" or "protocol relative" URI. In the spec since the beginning. Quite helpful to deal with http/https issues.

Read a much better description and caveats: Is it valid to replace http:// with // in a <script src="http://...">?

A few points to keep in mind:

  • There are some minor issues on IE 7 & 8 with double downloads
  • If you are viewing an HTML page from a file the browser will replace the scheme with file://, and not load your JS file from the server like it would with a full URL starting with http:// or https://.

Edit for modern webdev practices:

While the URL is still valid, it is now recommended to use https for third party resources (and, serve those resources from secure pages). The performance or compatibility issues from years ago are largely resolved with updated protocols and browsers.

查看更多
Anthone
3楼-- · 2019-01-25 04:07

It is valid indeed and I have just learned this in the hard way!! We broke a customization feature so you should always validate an URL like this (in .NET): Pay attention to:

  • White spaces (Trim)
  • "scheme relative" URI (UriKind.RelativeOrAbsolute)

    public bool IsValidUrl(string resourceUrl)
    {
        Uri uri;
        if (Uri.TryCreate(resourceUrl.Trim(), UriKind.RelativeOrAbsolute, out uri))
        {
            return uri.IsWellFormedOriginalString();
        }
    
        return false;
    }
    
查看更多
我只想做你的唯一
4楼-- · 2019-01-25 04:20

As a warning... we encountered issues with this methodology NOT being supported in Internet Explorer when used inside the HTML BASE tag (IE8 and 9 confirmed, didn't test any others before patching the issue).

After newly implementing SSL on a website, we had initially updated the BASE tags across the application to simply reference "//www.mydomain.com" : but the page templates broke (in IE only) on all scripts which did NOT live at the root of the site. Makes sense, since the BASE tag was not picking up the stylesheet or other relatively-linked resources which assumed they were being referenced from root, not from a nested location.

Since the BASE URI was our own domain anyway, we fixed the issue by setting the BASE tag's value to "https://www.mydomain.com". No matter if the client is browsing the site in SSL mode or out, at least it will work cross-browser now and can ALWAYS find its content - and by forcing https at all times, we ensure we don't get any content-mismatch warnings in the process by setting the BASE path to an http location while browsing a page using https.

查看更多
登录 后发表回答