开发者

Set cookies before subsequent requests in IE

I'm trying to set some cookies (via javascript) before the browser makes a request for various resources lower on the page. The following works in Chrome/Firefox, but, not IE:

开发者_如何学Go[some_page.html]

<!doctype html>
<head>
<script>
    var hash=new Date();
    document.cookie='hash=' + hash + ';';
    console.log("From page: " + hash);
</script>
<script src="/test_cookie.php"></script>
</head>
<body></body>
</html>

[test_cookie.php]

console.log('From script: <?=$_COOKIE['hash']?>');

When viewing some_page.html, I see the following in the console (in Chrome/Firefox):

"From page: 1316757967982"
"From script: 1316757967982"

Are there any tricks to get this to work in IE? Like setting defer on the test_cookie.php script tag, or, something else along those lines...?

Thanks!


You could dynamically generate the second script tag and inject it into the page so there's no way it could start before you had set the cookie. Then, if you're going to dynamically generate the script tag, it might actually be even better to add "?hash=1316757967982" onto the end of the test_cookie.php src URL so you could be guaranteed that your server gets the hash value (from the URL rather than the cookie). Then, you don't have to rely on cookie vs. script timing.

Here's how you dynamically add a script tag:

function addScriptTag(url) {
  var s = document.createElement(’script’);
  s.type=’text/javascript’;
  s.src= url;
  document.getElementsByTagName(’head’)[0].appendChild(s);
} 

addScriptTag("/test_cookie.php?hash=" + new Date());

There is no contract with the browser that it won't start loading multiple scripts at the same time, there's only a contract that it will execute statically defined scripts in sequential order so I don't think your current approach is ever guaranteed to work. Loading multiple scripts in parallel could easily be a desired browser speedup option.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜