1

Hello I am trying to create a script which inserts into any webpage a meta tag to force no-cache.

Currently this is my code and I dont want to use Jquery (as shown in Script to force IE8 cache behaviour).

var MAXlen = document.getElementsByTagName('head')[0].childNodes.length; 
//Get the length of childnodes of head.

while(MAXlen--)
{
 document.getElementsByTagName('head')[0].childNodes[MAXlen+1] = document.getElementsByTagName('head')[0].childNodes[MAXlen]; 
//store every node one place after.

 if(MAXlen == 0)
 document.getElementsByTagName('head')[0].childNodes[0].innerHTML = '<META HTTP-EQUIV="Pragma" CONTENT="no-cache">';
 //place this hmtlcode into the first element of head.
 break;
}
1
  • 1
    Welcome to SO. What exactly is your problem? Do you get an error? If so, provide information about this. Commented Jan 1, 2015 at 15:48

1 Answer 1

1

I would use ... prepend without JQuery:

parent.insertBefore(child, parent.firstChild);

parentNode.insertBefore(newChild, refChild);

Inserts the node newChild as a child of parentNode before the existing child node refChild. (Returns newChild.)

If refChild is null, newChild is added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).

In this case, you wouldn't need to loop through as in the code you presented.

UPDATE:

Try this with your code ...

var meta = document.createElement('meta');
meta.httpEquiv = "Pragma";
meta.content = "no-cache";
var head = document.getElementsByTagName('head')[0]
head.insertBefore(meta, head.firstChild);
  1. First, build the meta tag as a node.
  2. Then, capture the head tag as a variable.
  3. Using the variable, insert the node before the first child.

COMMENTS:

  • Tested functional in Chrome.
  • Tested functional in IE8 with console warning: "The code on this page disabled back and forward caching"
Sign up to request clarification or add additional context in comments.

7 Comments

Right idea; not enough detailed code to help the newbie OP. Show exactly how to add the meta tag. (Not that this approach would work in most browsers; not sure about IE8 (and don't care about IE8).)
Added the code to show this working. Tested in Chrome.
Correct code but beware of 2 important caveats: (1) The question is about IE8. Doesn't necessarily matter if it works on Chrome. (2) You can use JS to add <meta> tags, but (¿most?) browsers will not actually parse a <meta> tag added that way. IE8 might be an exception; doubt it.
Tested functional in IE8 ... "The code on this page disabled back and forward caching" Thanks for checking and reminding me.
Well then, it appears that IE8 does parse dynamically added <meta> tags. Good job!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.