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?