如果您不想使用脚本加载器,您可以使用以下方法,让您将 $(document).ready 脚本留在原处 - 修改如下:
$(()=>{
function checkAllDownloads() {
// Ensure your namespace exists.
window.mynamespace = window.mynamespace || {};
// Have each of your scripts setup a variable in your namespace when the download has completed.
// That way you can set async on all your scripts except jquery.
// Use the document ready event - this code - to check if all your scripts have downloaded.
if (window.mynamespace.script1 && window.mynamespace.script2){
// Proceed with page initialisation now that all scripts have been downloaded.
// [ Add your page initialisation code here ].
return;
}
// Not all downloads have completed.
// Schedule another check to give the async downloads time to complete.
setTimeout(checkAllDownloads, 500);
}
// check if it is safe to initialise the page by checking if all downloads have completed.
checkAllDownloads();
})