가젯 추가를 활용한 자동목차 넣는 방법
html 수정없이 가장 간단하게 자동목차를 구현할 수 있는 방법을 기존에 포스팅 했습니다.
구글 블로그 꾸미기 2 - 블로그스팟에 에 자동 목차를 넣는 가장 간단한 방법 (레이아웃에 가젯 추가로 간단하게 꾸미기)
저도 위의 가젯을 직접 제 구글 블로그에 삽입하고 활용해왔었죠.
그런데 어느 순간에서인가부터 불만이 생겼습니다.
로딩 속도가 느리다. 라는 불만이었습니다.기존에 공유 드렸던 코드는 이랬습니다.
이 가젯의 속도를 개선 했습니다.
이제는 포스팅 된 글을 클릭하면 바로 바로 목차가 디스플레이 됩니다.
그런데 어느 순간에서인가부터 불만이 생겼습니다.
로딩 속도가 느리다. 라는 불만이었습니다.기존에 공유 드렸던 코드는 이랬습니다.
가젯 추가로 구현하는 자동 목차 코드 (클릭하여 상자 열기)
<!-- 자동목차 -->
<script>
window.addEventListener("load", function () {
const content = document.querySelector(".post-body, .entry-content");
const postTitle = document.querySelector(".post-title, .entry-title");
if (!content || !postTitle) return;
const headings = content.querySelectorAll("h2, h3");
if (headings.length === 0) return;
const wrapper = document.createElement("div");
wrapper.style.border = "1px solid #ddd";
wrapper.style.borderRadius = "8px";
wrapper.style.padding = "1em";
wrapper.style.marginBottom = "2em";
wrapper.style.backgroundColor = "#f9f9f9";
wrapper.style.fontSize = "14px";
const tocTitle = document.createElement("div");
tocTitle.textContent = "목차";
tocTitle.style.fontWeight = "bold";
tocTitle.style.marginBottom = "0.5em";
tocTitle.style.fontSize = "16px";
wrapper.appendChild(tocTitle);
const tocList = document.createElement("ul");
tocList.style.listStyle = "none";
tocList.style.padding = "0";
tocList.style.margin = "0";
let h2Index = 0;
let h3Index = 0;
headings.forEach((heading, index) => {
const id = `toc-${index}`;
heading.setAttribute("id", id);
// scroll-margin-top으로 헤더와 겹치지 않게 처리
heading.style.scrollMarginTop = "100px";
const li = document.createElement("li");
li.style.marginBottom = "0.5em";
const link = document.createElement("a");
link.setAttribute("href", `#${id}`);
link.style.textDecoration = "none";
link.style.color = "#333";
const text = heading.textContent.trim().replace(/\s+/g, ' ');
if (heading.tagName === "H2") {
h2Index++;
h3Index = 0;
link.textContent = `${h2Index}. ${text}`;
li.style.marginLeft = "0";
} else if (heading.tagName === "H3") {
h3Index++;
link.textContent = `${h2Index}.${h3Index} ${text}`;
li.style.marginLeft = "3em";
link.style.fontSize = "13px";
}
li.appendChild(link);
tocList.appendChild(li);
});
wrapper.appendChild(tocList);
// 제목 다음이 아닌 본문 최상단에 목차 삽입
content.insertBefore(wrapper, content.firstChild);
});
</script>
이 가젯의 속도를 개선 했습니다.
이제는 포스팅 된 글을 클릭하면 바로 바로 목차가 디스플레이 됩니다.
가젯 추가로 구현하는 자동 목차 코드 - 속도 개선 (클릭하여 상자 열기)
<!-- 자동목차 속도 개선-->
<script>
document.addEventListener("DOMContentLoaded", function () {
const content = document.querySelector(".post-body, .entry-content");
const postTitle = document.querySelector(".post-title, .entry-title");
if (!content || !postTitle) return;
const headings = content.querySelectorAll("h2, h3");
if (headings.length === 0) return;
const wrapper = document.createElement("div");
wrapper.style.border = "1px solid #ddd";
wrapper.style.borderRadius = "8px";
wrapper.style.padding = "1em";
wrapper.style.marginBottom = "2em";
wrapper.style.backgroundColor = "#f9f9f9";
wrapper.style.fontSize = "14px";
const tocTitle = document.createElement("div");
tocTitle.textContent = "목차";
tocTitle.style.fontWeight = "bold";
tocTitle.style.marginBottom = "0.5em";
tocTitle.style.fontSize = "16px";
wrapper.appendChild(tocTitle);
const tocList = document.createElement("ul");
tocList.style.listStyle = "none";
tocList.style.padding = "0";
tocList.style.margin = "0";
let h2Index = 0;
let h3Index = 0;
headings.forEach((heading, index) => {
const id = `toc-${index}`;
heading.setAttribute("id", id);
heading.style.scrollMarginTop = "100px";
const li = document.createElement("li");
li.style.marginBottom = "0.5em";
const link = document.createElement("a");
link.setAttribute("href", `#${id}`);
link.style.textDecoration = "none";
link.style.color = "#333";
const text = heading.textContent.trim().replace(/\s+/g, ' ');
if (heading.tagName === "H2") {
h2Index++;
h3Index = 0;
link.textContent = `${h2Index}. ${text}`;
li.style.marginLeft = "0";
} else if (heading.tagName === "H3") {
h3Index++;
link.textContent = `${h2Index}.${h3Index} ${text}`;
li.style.marginLeft = "3em";
link.style.fontSize = "13px";
}
li.appendChild(link);
tocList.appendChild(li);
});
wrapper.appendChild(tocList);
content.insertBefore(wrapper, content.firstChild);
});
</script>
<!-- 자동목차 속도 개선-->
<script>
document.addEventListener("DOMContentLoaded", function () {
const content = document.querySelector(".post-body, .entry-content");
const postTitle = document.querySelector(".post-title, .entry-title");
if (!content || !postTitle) return;
const headings = content.querySelectorAll("h2, h3");
if (headings.length === 0) return;
const wrapper = document.createElement("div");
wrapper.style.border = "1px solid #ddd";
wrapper.style.borderRadius = "8px";
wrapper.style.padding = "1em";
wrapper.style.marginBottom = "2em";
wrapper.style.backgroundColor = "#f9f9f9";
wrapper.style.fontSize = "14px";
const tocTitle = document.createElement("div");
tocTitle.textContent = "목차";
tocTitle.style.fontWeight = "bold";
tocTitle.style.marginBottom = "0.5em";
tocTitle.style.fontSize = "16px";
wrapper.appendChild(tocTitle);
const tocList = document.createElement("ul");
tocList.style.listStyle = "none";
tocList.style.padding = "0";
tocList.style.margin = "0";
let h2Index = 0;
let h3Index = 0;
headings.forEach((heading, index) => {
const id = `toc-${index}`;
heading.setAttribute("id", id);
heading.style.scrollMarginTop = "100px";
const li = document.createElement("li");
li.style.marginBottom = "0.5em";
const link = document.createElement("a");
link.setAttribute("href", `#${id}`);
link.style.textDecoration = "none";
link.style.color = "#333";
const text = heading.textContent.trim().replace(/\s+/g, ' ');
if (heading.tagName === "H2") {
h2Index++;
h3Index = 0;
link.textContent = `${h2Index}. ${text}`;
li.style.marginLeft = "0";
} else if (heading.tagName === "H3") {
h3Index++;
link.textContent = `${h2Index}.${h3Index} ${text}`;
li.style.marginLeft = "3em";
link.style.fontSize = "13px";
}
li.appendChild(link);
tocList.appendChild(li);
});
wrapper.appendChild(tocList);
content.insertBefore(wrapper, content.firstChild);
});
</script>
만약 위의 코드를 보시거나 복사에 어려움이 있으시면 옆의 링크를 클릭해주세요. : 링크
위의 코드의 사용법을 모르시면, 제가 이글의 상단에서 링크 건 글을 참조해주세요.
구글 블로그의 일반적인 가젯 설정에 대해서 궁금하시다면, 이 글을 참조하세요.
아래 내용은 위의 코드를 수정할때 참고할 세부 사항들입니다.
📌 1. wrapper (목차 전체 박스)
속성 | 의미 | 조정 팁 |
---|---|---|
border | 박스 외곽 테두리 | "none"으로 제거 가능, 색상은 #ccc 등으로 조정 |
borderRadius | 테두리 둥글기 | 0px = 직각, 12px 이상은 더 둥글어짐 |
padding | 내부 여백 | 1em = 약 16px, 1.5em이면 더 넉넉함 |
marginBottom | 목차 아래 여백 | 다음 단락과 간격 확보용 2em 등 |
backgroundColor | 배경색 | #f9f9f9 → 연회색, #fff9c4 → 레몬톤 추천 |
fontSize | 전체 글자 크기 | 13px~16px 범위 권장 |
📌 2. tocTitle (‘목차’ 글자 설정)
- textContent: "목차" → "CONTENTS", "INDEX" 등으로 변경 가능
- fontWeight: "bold" 또는 600~800 설정
- marginBottom: 제목과 리스트 사이 간격. 0.5em~1em
- fontSize: 16px (기본), 강조 시 18px
📌 3. tocList (목차 목록 전체 설정)
- listStyle: 기본 불릿 여부. none 유지 권장
- padding, margin: 내부 여백 제거 (0), 필요 시 "0 0 0.5em" 등으로 조절
📌 4. li (각 항목 간격 및 들여쓰기)
- marginBottom: 줄 간격. 0.3em~1em 범위 조절 가능
- marginLeft (h3만): 들여쓰기 깊이. 3em은 약 48px
📌 5. link (각 항목 텍스트 스타일)
- textDecoration: 링크 밑줄 여부 ("none" or "underline")
- color: 링크 색상. #333(기본), #007BFF 등 강조 색 가능
- fontSize (h3만): 소제목 글자 크기. 12px~14px
📌 6. scrollMarginTop (제목 클릭 시 위 여백 확보)
- scrollMarginTop: 고정 헤더 있을 경우 100px~150px 추천
- 없다면 0 또는 50px로 줄여도 무방
✳️ 스타일 조정 팁
- 미니멀 스타일: border 없음, 배경 투명, 글자 작게
- 가독성 강조: 배경색 있음, 제목 폰트 크고 굵게
- 접기/펼치기 기능 추가도 가능 (JavaScript 필요)
댓글 쓰기