Skip to content

Commit 11aad45

Browse files
committed
feat(tampermonkey): Improve GitHub contributions script with dynamic element loading
Enhance the script to use a MutationObserver for waiting for the yearly contributions element, making the script more robust and reliable. Bump version to 0.0.5.
1 parent a6158a7 commit 11aad45

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

tampermonkey-scripts/show-all-contributions.js

+28-6
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// @name Show all contributions by year in the GitHub profile
33
// @name:zh-CN 在 GitHub profile 页面以年份展示用户所有的贡献
44
// @namespace https://github.com/kang8
5-
// @version 0.0.4
5+
// @version 0.0.5
66
// @updateURL https://raw.githubusercontent.com/kang8/.dotfiles/master/tampermonkey-scripts/show-all-contributions.js
77
// @downloadURL https://raw.githubusercontent.com/kang8/.dotfiles/master/tampermonkey-scripts/show-all-contributions.js
88
// @description Show all contributions by year since the user was created in the GitHub profile page
@@ -18,8 +18,9 @@
1818
(async function () {
1919
'use strict';
2020

21-
// Wait for 1.5 seconds for the DOM to load.
22-
await new Promise((resolve) => setTimeout(resolve, 1500));
21+
const contributionsLastYearSelector = 'div.js-yearly-contributions > div:nth-child(1)'
22+
23+
await waitForElement(contributionsLastYearSelector);
2324

2425
const pathArr = location.pathname.split('/');
2526

@@ -34,9 +35,7 @@
3435
) {
3536
const userId = pathArr[1];
3637

37-
const contributionsLastYear = document.querySelector(
38-
'div.js-yearly-contributions > div:nth-child(1)',
39-
);
38+
const contributionsLastYear = document.querySelector(contributionsLastYearSelector);
4039

4140
const contributionsAllYearsDiv = document.createElement('div');
4241
contributionsAllYearsDiv.className = 'position-relative border';
@@ -148,3 +147,26 @@ function getYearByContributionsCalendar(childNode) {
148147
'',
149148
).slice(-4);
150149
}
150+
151+
/**
152+
* @param {string} selector
153+
*/
154+
function waitForElement(selector) {
155+
return new Promise((resolve) => {
156+
if (document.querySelector(selector)) {
157+
return resolve(document.querySelector(selector));
158+
}
159+
160+
const observer = new MutationObserver(() => {
161+
if (document.querySelector(selector)) {
162+
observer.disconnect();
163+
resolve(document.querySelector(selector));
164+
}
165+
});
166+
167+
observer.observe(document.body, {
168+
childList: true,
169+
subtree: true
170+
});
171+
});
172+
};

0 commit comments

Comments
 (0)