I want to inject html markup into a div in multiple sites in different platforms. Ideally it would look something like this where each developer can insert a script tag to my js. Lets assume each application has bootstrap and jquery.
<script id="globalheaderapi" src="https://www.url.com/globalheader.js"></script>
and html would only be something like this on the applications
<header id="globalHeader"></header>
I want to insert my html markup inside header. I would also want to js to insert link to css source.
The question is, the apps only have jquery.
$( document ).ready(function() {
//insert link to header css
$('head').append('<link rel="stylesheet" href="globlalHeader.min.css" type="text/css" />');
//insert html in div
$( "#globalHeader" ).html( "<nav><ul><li><a href="link">Home</li><li><a href="link">About</li></ul></nav>" );
});
Update
I tried $( "#globalHeader" ).load(...
and it works if js and the app is in the same domain if i try it in a different domain i get the crosssite error
XMLHttpRequest cannot load http://url . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
jQuery is embedded into the <script> tag of HTML file between the <head> tag and the <title> tag.
jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
Include the jQuery by CDNStep 1: Firstly, we have to open that Html file in which we want to add the jQuery using CDN. Step 2: After then, we have to place the cursor between the head tag just before the title tag. And, then we have to use the <script> tag, which specify the src attribute for adding.
html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
Taking for granted that there is a decent enough reason in your environment to not just use server side includes or something more straightforward, jQuery's .load() seems like it would suit you. You'd just stub out the HTML you'd want to inject and have each page call it like this:
$("#globalHeader").load('globalHeader.html');
Your CSS injection looks fine, though I'm curious why if you have access to the site to insert a script tag you can't just add the link tag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With