问题
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:
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);
- First, build the meta tag as a node.
- Then, capture the head tag as a variable.
- 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"
来源:https://stackoverflow.com/questions/27732140/no-cache-script-without-using-jquery