Last active
June 24, 2022 09:18
-
-
Save scil/f97d53cb3194397976cb2fa8478f0793 to your computer and use it in GitHub Desktop.
window.onload with addicional feature to support pjax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* feature: function `f` only execute once. | |
* @param function `f` | |
* @param string `id` for debug | |
*/ | |
function addOnload(f, id) { | |
// to prevent f excute twice, as f is registered to both onload and 'pjax:ready' | |
f.n = 1; | |
var o = window.onload, F = function () { | |
id && console.log(`[ want to run ${id}`) | |
if (f.n) { | |
f(); | |
id && console.log(` ]. runed ${id}`) | |
} | |
f.n = 0 | |
}; | |
// solution from: https://stackoverflow.com/questions/3698200/window-onload-vs-document-ready/19846508#19846508 | |
"function" != typeof o ? window.onload = F : window.onload = function () { | |
o && o(), F() | |
} | |
// event `pjax:content` is not approprate. If F registered with that event, F not executed until next page load. | |
document.addEventListener('pjax:ready', F, {once:1}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment