Search code examples
javascriptcontent-management-systemhead

How can I insert CSS, META, etc. tags into the head tag using Javascript?


I use a hosted CMS that has a bug that won't allow me to insert content into the <head>.

I thought about using Javascript to insert the code needed into the head but will that even work? If a page is read <head> then <body> will it even matter to put the code into the head using javascript if the head has already been read or do I mis-read how the browsers work?

If you can put content into the head of a page and it will work with all major browsers what is the javascript to do that? (I am a novice when it comes to javascript.)

Note: I use a hosted CMS and do not have access to any server side scripting.

EDIT:

I need to add CSS and META tags.

The CSS would be something like this:

<style type="text/css">
 .slideshow img { display: none }
 .slideshow img.first { display: block }
</style>

The META could look like this:

<meta property="og:title" content="Title Text" />
<meta property="og:type" content="article" />
<meta property="og:url" content="URL Path" />
<meta property="og:image" content="IMG Path" />
<meta property="og:image:type" content="image/jpeg" />
<meta property="og:image:width" content="620" />
<meta property="og:image:height" content="541" />
<meta property="og:site_name" content="My Site" />

Those are examples but similar to what I will be adding.


Solution

  • For a CSS script:

    var ele = document.createElement("style");
    ele.type = "text/css";
    ele.innerHTML = "CSS CODE"; // Replace with CSS code.
    document.head.appendChild(ele);
    

    For the Meta Tag (although I doubt it would work, since the software that looks at Meta Tags usually doesn't execute JavaScript code):

    var ele = document.createElement("meta");
    ele.property = "propertyName"; //Replace with property name.
    ele.content = "CSS CODE"; // Replace with content.
    document.head.appendChild(ele);