Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting

<script type="text/javascript" src="js/new.js" defer></script>
into every .html file header. This has led to a lot of duplicated code and maintenance headaches.

Recently, I discovered a convenient solution for stylesheets by importing one master.css stylesheet in all .html file headers. Now, I simply add new styles to master.css to avoid repetition. The content of master.css is structured 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 query pertains to whether there is a similar JavaScript approach to group HTML header imports as shown above. I experimented with $.getScript("test.js");, but it doesn't seem to execute the script in the same manner as using <head> tags. Additionally, it behaves oddly with the defer attribute.

Answer №1

If I were to use vanilla JavaScript, I would approach it like this:

// index.html
<script src="./index.js"></script>

// index.js
let scriptElement = document.createElement("script");
scriptElement.setAttribute("src", "./t.js");
scriptElement.setAttribute("async", "false");
scriptElement.setAttribute("defer", true);
document.head.appendChild(scriptElement);

let scriptElement1 = document.createElement("script");
scriptElement1.setAttribute("src", "./t1.js");
scriptElement1.setAttribute("async", "false");
scriptElement1.setAttribute("defer", true);
document.head.appendChild(scriptElement1);

// Feel free to refactor and utilize an array of source URLs

By doing this, you only need to update one JavaScript file instead of multiple HTML files

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What measures can be taken to deter users from navigating to a different webpage?

This HTML code includes an image that is linked to another page. <a href="#" class="dead_prfile_step_next ADInNext"> <img alt="next" src="/Content/DesignFiles/@Html.R(VirtualPath, "dead_profile_free_buttons_next.png")" /> </a> Here is ...

What is the method for implementing a timeout in axios when utilizing the proxy option?

When using Axios with the proxy option, I wanted to verify bad proxies by setting a timeout on my GET request. Here is the code snippet: let res = await axios.get(`http://somedomain.com`, { timeout: 1500, proxy: { ...

Error in Vue component when setting the background image URL

Here is my code snippet that sets the background image for a component: style() { return { "background-image": `url(${require(`../../../assets/images/${this .last_result}.png`)})` }; }, The expected URL should be ../../../assets/images/ ...

Best practices for bulk inserting sequences in Node.js using MySQL

I have a dataset ready to be inserted into a MySQL database using nodejs. Here is the code I've written: con.connect(function (err) { myArray.forEach((el)=>{ con.query(1stQuery,1stValue,(error,result)=>{ //do something with ...

Error: pos variable is not defined

I encountered a TypeError: pos is undefined while running the code below. $(document).ready(function() { var s = $("#col-scroll"); var pos = s.position(); $(window).scroll(function() { var windowpos = $(window).scrol ...

Managing errors with Node.js and handling https certificates

In short: I am developing a node application that sends requests using the secure version of HTTP, which is HTTPS. When I incorrectly configure my request options, I encounter the following error: Node.js Hostname/IP doesn't match certificate' ...

Challenges with moving images in Unslider

There seems to be an issue with the unslider-arrows on the unslider banner. The images are not sliding properly when transitioning to the next image without user input. Instead, they resize from small to full size starting at the top of the .banner div. ...

Textbox with Placeholder Text and Entered Data

When working with an HTML input box to enter a value that will be used to run a PHP script, it is possible to pass that value using the URL and GET method. To enhance user experience, I wanted to add a watermark hint in my textbox. After some research, I ...

Tips for choosing the desired test to execute with Nightwatch Programmatic API

Currently, I am in the process of developing a web application that enables me to execute Nightwatch tests through a visual interface. At this point, I have successfully been able to run all my tests using a post request from my web app utilizing the Nig ...

Strange yellow border appears when key is pressed in Quasar's QLayout

While working on a project with the quasar framework and electron.js, I encountered a strange bug where pressing a key causes the application frame to display a persistent yellow border. This border cannot be overridden, removed, or selected using devtools ...

store JSON data within an HTML list element

I've been working on a JavaScript script that allows me to generate list items in HTML. Right now, I have functionality to drag and remove the items using another script. However, I am interested in adding some additional information to each list item ...

What are the steps for adding information to a MySQL database with GWT, HTML, and either JDBC or Hibernate?

I have been working with GWT (Google Web Toolkit) version 2.5.1 and successfully developed a sample application to display the username and password. However, I am now facing challenges in inserting these values into a MySQL database table using JDBC or Hi ...

CSS slider experiencing issues

I'm currently working on creating a custom CSS ticker by referencing various examples online. I've managed to develop something that functions well, but it seems to only cycle through the initial 4 list items. Once it reaches the 4th item, it loo ...

C# fails to accurately interpret JSON Arrays

I'm dealing with a peculiar JSON issue. I am currently using ASP C# and have a View that sends a JS-Array to a Controller Action. Here is the JSON Data structure: public class MapData { public List<Point> Points { get; set; } } public cla ...

Tips to position two shortcode elements next to each other horizontally

I have some code here and I am looking to align the two elements at the bottom, "php echo do_shortcode(wcas-search-form);" and "php do_action('hamzahshop_custom_min_cart');" on the same line horizontally. I am new to this and struggling to figure ...

Utilizing jQueryUI for rendering tabbed content with JSON data

Although I have the ability to load JSON data that is returned (appearing "as is" in my HTML page), I am facing an issue where the raw JSON data does not disappear. The code I have used is as follows: $( "#tavole" ).tabs({ cache : false, event: "m ...

Blending HTML elements with ASP.NET code

Trying to concatenate two strings separated by a line break. This snippet shows what I am attempting: <td>@(string.Join("<br /> ", report.TimeReportProjects.Select(x => x.Project.ProjectName)))</td> <td>@(string.Join("<br /& ...

Utilize Bootstrap to combine two tables within a single column efficiently

I am facing an issue with my layout that involves organizing 3 tables in a specific way. Two smaller tables are supposed to take up 3 bootstrap columns on the left side, while one larger table should occupy 9 columns on the right side. However, when I impl ...

When trying to click on an HTMLTableRowElement, an Uncaught ReferenceError occurs in React.js and jQuery, stating that the function is

When I was working on my web app, I encountered an issue while trying to create a table. Upon clicking on it, I received an error message: Uncaught ReferenceError: (function) is not defined at HTMLTableRowElement.onclick Here is the code for the table: $( ...

Enhance your web form with an auto-suggest textbox that allows for multiple selections,

Looking for assistance in implementing an auto complete text box with the ability to select multiple options using Dojo. Any experts out there who can offer their guidance? ...