问题
I am attempting to load all js files using approach explained in this video @3:30 Optimize your code: load code at the right time
I have implemented this approach in index.js as
<script>
var scripts = '<script src="./js/jquery-3.5.1.min.js"/>'+
'<script src="./js/jquery-ui.min.js"/>'+
'<script src="./js/bootstrap.min.js"/>'+
'<script src="./js/index.js"/>';
$(window).on("load",function(){
$("body").append(scripts)
});
</script>
also tried as in html head tag
<script>
var scripts = '<script src="./js/jquery-3.5.1.min.js"/>'+
'<script src="./js/jquery-ui.min.js"/>'+
'<script src="./js/bootstrap.min.js"/>'+
'<script src="./js/index.js"/>';
$(window).on("load",function(){
$("body").append(scripts)
});
</script>
still it does not loads all js files which I am passing in script tags and not loading in network tab as well.
My question are
- Is this really better approach to load all script like this and must be followed all the times?
- If yes What I need to optimize above code so that it will load entire scripts and append to html?
回答1:
jQuery isn't loaded yet so you can't use it. So i suggest you use a vanilla javascript solution. (Add as inline script tag right before the closing body tag </body>
)
const scripts = [
"./js/jquery-3.5.1.min.js",
"./js/jquery-ui.min.js",
"./js/bootstrap.min.js",
"./js/index.js",
];
window.addEventListener("DOMContentLoaded", () => {
for(const script of scripts) {
const scriptTag = document.createElement("script");
scriptTag.src = script;
document.body.appendChild(scriptTag);
}
});
EDIT: If you need the scripts to load in a particular order. You can use the "load" event to start the next one. See snippet below
const scripts = [
"./js/jquery-3.5.1.min.js",
"./js/jquery-ui.min.js",
"./js/bootstrap.min.js",
"./js/index.js",
];
window.addEventListener("DOMContentLoaded", () => loadScript(scripts, 0));
function loadScript(scripts, index) {
if (!scripts[index]) return;
const scriptTag = document.createElement("script");
scriptTag.src = scripts[index];
scriptTag.addEventListener("load", () => loadScript(scripts, index + 1));
document.body.appendChild(scriptTag);
}
来源:https://stackoverflow.com/questions/63724492/what-is-the-right-way-to-append-all-js-files-using-jquery-append