CDN에서 부트 스트랩을 사용하거나 서버에서 복사해야합니까?
Twitter 부트 스트랩을 사용하는 가장 좋은 방법은 무엇입니까, CDN에서 참조하거나 서버에 로컬 사본을 만드시겠습니까?
부트 스트랩이 계속 발전하고 있기 때문에 CDN을 참조하면 시간이 지남에 따라 다른 웹 페이지가 표시되고 일부 태그가 손상 될 수 있습니다. 대부분의 사람들의 선택은 무엇입니까?
왜 둘 다 ¯ \ _ (ツ) _ / ¯? Scott Hanselman은 성능 향상을 위해 CDN을 사용하는 방법에 대한 훌륭한 기사를 가지고 있지만 CDN이 다운 된 경우 로컬 복사본으로 우아하게 되돌아갑니다 .
부트 스트랩과 관련하여 다음을 수행하여 로컬 폴 백이있는 CDN에서로드 할 수 있습니다 .
플 런커 작업 데모
<head>
<!-- Bootstrap CSS CDN -->
<link rel="stylesheet" href="~https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
<!-- Bootstrap CSS local fallback -->
<script>
var test = document.createElement("div")
test.className = "hidden d-none"
document.head.appendChild(test)
var cssLoaded = window.getComputedStyle(test).display === "none"
document.head.removeChild(test)
if (!cssLoaded) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = "lib/bootstrap.min.css";
document.head.appendChild(link);
}
</script>
</head>
<body>
<!-- APP CONTENT -->
<!-- jQuery CDN -->
<script src="~https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- jQuery local fallback -->
<script>window.jQuery || document.write('<script src="lib/jquery.min.js"><\/script>')</script>
<!-- Bootstrap JS CDN -->
<script src="~https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
<!-- Bootstrap JS local fallback -->
<script>if(typeof($.fn.modal) === 'undefined') {document.write('<script src="lib/bootstrap.min.js"><\/script>')}</script>
</body>
업데이트
- YepNope 또는 fallback.js를 사용하여 동일한 테스트 를 수행 할 수도 있습니다.
- 당 플래시의 의견 과 이 솔루션 , 확인하기 위해 대답을 업데이트
.visible
를 테스트하는 대신 클래스rgb(51, 51, 51)
- 당 deste의 코멘트를 사용하도록 업데이트,
.hidden
및.d-none
중 부트 스트랩 3.x 또는 4 - 스타일 시트가로드되었는지 테스트 할 때 적용 할 스타일을 찾고 요소를 작성하고 적용되었는지 확인해야합니다.
- 바닐라 js를 사용하여 헤드에 즉시로드되도록 스타일 시트를 업데이트했습니다. 을 사용하여 테스트 요소를 작성하고
Document.createElement()
부트 스트랩 클래스를 적용하고을Window.getComputedStyle()
테스트하고 js를 사용하여display:none
조건부 로 스타일 시트 를 삽입해야합니다 .
모범 사례
To your question on Best Practices, there are a lot of very good reasons to use a CDN in a production environment:
- It increases the parallelism available.
- It increases the chance that there will be a cache-hit.
- It ensures that the payload will be as small as possible.
- It reduces the amount of bandwidth used by your server.
- It ensures that the user will get a geographically close response.
To your versioning concern, any CDN worth its weight in salt with let you target a specific version of the library so you don't accidentally introduce breaking changes with each release.
Using document.write
According to the mdn on document.write
Note: as
document.write
writes to the document stream, callingdocument.write
on a closed (loaded) document automatically callsdocument.open
, which will clear the document.
However, the usage here is intentional. The code needs to be executed before the DOM is fully loaded and also in the correct order. If jQuery fails, we need to inject it into the document inline before we attempt to load bootstrap, which relies on jQuery.
HTML Output After Load:
In both of these instances though, we're calling while the document is still open so it should inline the contents, rather than replacing the entire document. If you're waiting till the end, you'll have to replace with document.body.appendChild
to insert dynamic sources.
Aside: In MVC 6, you can do this with link and script tag helpers
Depends on the specific site.
Do you have many users? Do you care about bandwidth usage? Is performance an issue (CDN's can speed up the responses) ?
You can link to a specific version:
//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css
Or
//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css
That way you don't have to worry about library updates, its a better practice to keep updated.
I am not sure what are the exact statistics about developers choice, but you can have a look here and see Billions of requests are sent to Bootstrap CDN, which means it is robust and safe to use.
I tried to edit the KyleMit's answer but the forum was marking as a wrong indented code, even it wasn't, so I'm adding my contribution right bellow:
As the question is tagged as a twitter-bootstrap topic (and not only twitter-bootstrap-3 ), maybe it's helpful to update the response for the newer version of Bootstrap.
As the framework added a new class for hiding elements on its fourth version, we should use .d-none
instead of .hidden
in this case.
Everything else remains the same on that case, except the lib version (of course!)
Thanks to @KyleMit. Another way of fall back is using 'window' object as under -
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script>
window.jQuery || document.write("<script src='js/jquery.min.js'><\/script>");
</script>
It works like this - If the CDN link works, 'window' object will have 'jQuery' property available else the second part of the script i.e. document.write will get executed which points to the local copy.
Answer to original question - Having CDN has many benefits such as quick downloads without impacting your server and bandwidth. Having a local copy has its own benefit (as a fall back arrangements). On intranet, due to proxy settings, security policies, CDN link may not work or if CDN link is down it may not work. The straight answer is to have both.
Almost all public CDNs are pretty reliable. However, if you are worried about that fraction of the time when a CDN might be down, you can load Bootstrap from one Bootstrap CDN, and fallback to an alternative CDN in case the first one is down.
<html>
<head>
<!-- Bootstrap CSS CDN with Fallback -->
<link rel="stylesheet" href="https://pagecdn.io/lib/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha256-YLGeXaapI0/5IgZopewRJcFXomhRMlYYjugPLSyNjTY=" crossorigin="anonymous">
<script>
var test = document.createElement("div")
test.className = "hidden d-none"
document.head.appendChild(test)
var cssLoaded = window.getComputedStyle(test).display === "none"
document.head.removeChild(test)
if (!cssLoaded) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css";
document.head.appendChild(link);
}
</script>
</head>
<body>
<!-- APP CONTENT -->
<!-- jQuery CDN with Fallback -->
<script src="https://pagecdn.io/lib/jquery/3.2.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"><\/script>');</script>
<!-- Bootstrap JS CDN with Fallback -->
<script src="https://pagecdn.io/lib/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha256-CjSoeELFOcH0/uxWu6mC/Vlrc1AARqbm/jiiImDGV3s=" crossorigin="anonymous"></script>
<script>if(typeof($.fn.modal) === 'undefined') {document.write('<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"><\/script>')}</script>
</body>
</html>
두 번째 관심사 정보 : 이 게시물의 링크는 하드 코딩 된 버전의 부트 스트랩 및 jquery입니다. 따라서 부트 스트랩과 jquery 라이브러리가 지속적으로 개발되고 새로운 기능을 사용하더라도 사이트는 시간이 지남에 따라 동일하게 유지됩니다.
'development' 카테고리의 다른 글
PostgreSQL이 인덱스 열에서 순차적 스캔을 수행하는 이유는 무엇입니까? (0) | 2020.07.04 |
---|---|
힘내 : 특정 커밋에 리베이스하는 방법? (0) | 2020.07.04 |
Chrome의 '미 발견 TypeError : 잘못된 호출' (0) | 2020.07.04 |
Electron / Atom Shell 앱의 앱 아이콘을 설정하는 방법 (0) | 2020.07.04 |
IntelliJ의 RegEx 역 참조 (0) | 2020.07.04 |