Dynamically insert JavaScript and CSS files into the header by using the append method

Due to a specific reason, I am loading CSS and scripts into my head tag using the "append" method. For example:

$("head").append('<script type="application/javascript" src="core/js/main.js"></script>');

I'm asynchronously pulling HTML content ("ajax way") that requires certain styles and script functions, hence why I load the script and CSS along with it.

Below is the code I am using:

$.ajax({
    url : 'page_loader.php',
    dataType: 'html',
    data : { page_name : 'test' },
    type: 'get',
    beforeSend : function(){
        //show a spinner
        $("#spinner").show();
    },
    success : function(data){
        //load the CSS before contents
        $("head").append('<link rel="stylesheet" type="text/css" href="core/css/main.css" />');
        //load the pulled HTML contents into the div with an id of ajax_page
        $("#ajax_page").html(data);
        //then load the script in the head
        $("head").append('<script type="application/javascript" src="core/js/main.js"></script>');
        //hide the spinner
        $("#spinner").hide();
    }
});

Everything is functioning properly, but I want to avoid duplicating or multiplying the script and link every time the content is loaded. Currently, using the append method will duplicate the script and CSS if the ajax function is called more than once. Is there a way to prevent this duplication, like loading them only once? Or is it acceptable for them to be loaded multiple times if the ajax runs multiple times?

PS: I am considering assigning an ID to the link and script so I can check if they already exist before loading them. Is it valid to add an ID to the link and script tags?

Answer №1

JavaScript offers the fetch method for loading external JS files.

About: Retrieve a JavaScript file from a server using a GET HTTP request and then run it.

fetch(url)
    .then(response => response.text())
    .then(data => {
        // do something with the data
    });

Further Reading:

fetch method

Answer №2

I am unsure if using ID is permissible on the link or script tag, but alternatively, you could target elements based on their href attribute.

if ($('link[href="styles/main.css"]').length == 0) {
    $("head").append('<link rel="stylesheet" type="text/css" href="styles/main.css" />');
}

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

The assets path is the directory within the installed package that houses the main application files following the completion of a

I have a Vue.js UI component that is internally built using webpack. This reusable UI component library references its images as shown below: <img src="./assets/logo.png"/> <img src="./assets/edit-icon.svg"/>   <i ...

Deliver a message using a loop in jade

I'm struggling with posting a request in Node and Jade using a specific ID. For instance, if Node returns a list of books : res.render('tests', {books: books}); In my Jade template, I display all the books by iterating through them. b ...

The error message "node-soap - callback is not a function" is indicating that there

Encountering a common TypeScript error while calling a SOAP method on a node-soap client in NodeJS. Seeking guidance on resolving this issue. https://www.npmjs.com/package/soap - version: 0.35.0 Sample Code Snippet const [result] = await mySoapClient.Per ...

What is the best way to reveal CSS files downloaded via npm?

I'm currently working on a Sass/CSS library that I have hosted on npm. I am exploring ways to make it easier for clients to access it, such as using: @import 'library_name' Instead of the less appealing option: @import 'node-modules/ ...

Tips for incorporating several d3 elements on a single webpage

I am currently facing an issue where I am attempting to add a line graph below a d3 map, but the map and line graph are appearing below where the map should be located. I have tried creating separate div tags with distinct id's, but I am unsure of wha ...

Use Express 4.x to automatically redirect HTTP traffic to HTTPS

Here is the code snippet that I am working with: var https = require('https'); var http = require('http'); var express = require('express'); var app = express(); var router = express.Router() ...

Aligning input and submit fields perfectly in the same line

Struggling to get an input form and submit button to align perfectly in Firefox and Safari. Any advice? Here's the current CSS for the 'Keep in touch' widget on www.landedhouses.co.uk: form.mc4wp-form p{margin-left:0px !important; display: ...

At what point do browsers decide to round pixel fractions to whole pixels, and when do they choose not to do

I recall reading here on SO that using pixel fractions in CSS is generally advised against because browsers tend to round them to the nearest whole pixel. As shown in the example below, 0.3 pixels are indeed rounded to a full pixel: span { border: 0. ...

A guide on using key arrows in JavaScript to navigate and focus on elements

When working on my HTML project, I have a list of elements that I want to be able to select using the arrow keys. I've included my code here for reference: [http://jsfiddle.net/T8S7c/] What I'm trying to achieve is when the arrow keys are press ...

Getting the value of a radio button in an array list using Ajax

I have a form with multiple radio lists set up like this: <div id="Question[180]"> <input name="Question[180]" id="6" value="6" class="inputbox" size="1" type="radio">yes <input name="Question[180]" id="7" value="7" class="inputbox" ...

Jquery feature to automatically hide the submit button

Is there a way to automatically hide the submit button and display a message without requiring a mouse click? If the main balance is less than the inputted withdrawal amount, I want the submit button to be hidden automatically and a message stating insuff ...

Leveraging regex match.map to incorporate a React <img> tag within a given string

One of my recent discoveries involves replacing a string completely with React image elements, as demonstrated in the following code snippet: if (source.match(/\{([0-z,½,∞]+)\}/g)) { tagged = source.match(/\{([0-z,½,∞]+)\ ...

When a React page is re-rendered using useEffect, it automatically scrolls back to the

Every time I utilize the <Tabs> component, the onChange method triggers the handleTabChange function. This leads to the component being called again and after repainting, the useEffect is triggered causing the page to scroll back to the top. How can ...

Code snippet: Retrieve the previous and upcoming events based on the current date from an array (JavaScript/Angular)

Is there anyone who can assist me with an algorithm? I have a list of events and need to retrieve the next event and previous events based on the current date. For example: I fetch all events from an SQL database like so: events = [ {eventId:1, event ...

Designing a unique shape geometry using THREE JS

I've been struggling to replicate an existing city in a 3D environment using THREE.js. I have coordinates for approximately 1000 buildings, each with a varying number of corners making it impossible to use standard cubeGeometry. I attempted to create ...

Retrieve the text value from a single object by utilizing jQuery

I am struggling with customizing a product page that lists various products in a list format. My goal is to create an alert that displays only the name of the product when clicked, rather than showing both the name and price as it currently does. Can someo ...

The sweetalert 2 input field is unresponsive or disabled within a materializecss modal, making it impossible to type in

My modal includes a SweetAlert2 popup when I click the "add bills" button. The code for this feature is from their documentation, so I don't believe the issue lies there. However, I am experiencing a problem where the input field is not type-able and ...

Can a single button click be shared across multiple forms?

The main concept involves a grid where when a user double-clicks on a row, a modal window (Bootstrap panel) opens with a panel-body section for editing the data and a panel-footer containing a btn-group for actions like "Save", "Cancel", or "Close". This s ...

Tips for adjusting a pre-filled form?

When a form is rendered by onClick from a component, it loads with values. I want to be able to edit these current values and then perform an update operation. Here is the link to the sandbox: https://codesandbox.io/s/material-demo-forked-e9fju?file=/demo ...

Tips for synchronizing text field and formula field content on MathQuill 0.10

I am currently working on creating a WYSIWYGish input element for my formula, along with a LaTeX input element. <span id="editable-math" class="mathquill-editable"></span> The goal is to make these two elements work synchronously. Here's ...