My code currently looks something like:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
...
<link rel="stylesheet" href="css/master.css"> <!-- One stylesheet to import them all. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js" defer></script>
<script type="text/javascript" src="js/collapsibles.js" defer></script>
<script type="text/javascript" src="js/imports.js" defer></script>
<script type="text/javascript" src="js/topnav.js" defer></script>
</head>
<body>
...
and the issue is that these header script imports appear in very many places. This results in a lot of duplicated code, and whenever I want to add a new script, I have to add the <script type="text/javascript" src="js/new.js" defer></script>
into every .html
file header manually. I've recently found a very nice solution to this with stylesheets, where I now import one master.css
stylesheet in all .html
file headers, and then I can add new styles into master.css
, which looks something like this:
/* Register all base website imports here. */
@import url(base.css);
@import url(home.css);
@import url(topnav.css);
@import url(containers.css);
...
My question is, is there any JavaScript equivalent for grouping HTML header imports (similar to the one I've shown above)? I've tried $.getScript("test.js");
, but I don't think it's executing the script in the same way the <head>
tags are doing. It also seems to work strangely with the defer
command..
CodePudding user response:
with a vanilla JS I would make like that:
// in index.html
<script src="./index.js"></script>
//in index.js
let scriptEle = document.createElement("script");
scriptEle.setAttribute("src", "./t.js");
scriptEle.setAttribute("async", "false");
scriptEle.setAttribute("defer", true);
document.head.appendChild(scriptEle);
let scriptEle1 = document.createElement("script");
scriptEle1.setAttribute("src", "./t1.js");
scriptEle1.setAttribute("async", "false");
scriptEle1.setAttribute("defer", true);
document.head.appendChild(scriptEle1);
// sure, you may refactor and use an array of src urls
Now you need to modify only one JS file instead of each html files