0

The $script.js library I am using

https://github.com/ded/script.js/

has the following Javascript. What I need to do is set the request header in this code block but I am not sure how to do this:

var el = doc.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
  if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
    return false;
  }
  el.onload = el.onreadystatechange = null;
  loaded = true;
  // done!
};
el.async = true;
el.src = path;
document.getElementsByTagName('head')[0].insertBefore(el, head.firstChild);

Here's an example of something similar (not part of $script.js) that does set the request header:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);

The first code block (the one I need to use but can modify slightly) is not very clear to me. Does anyone know how I can change this first code blocks (used in $script.js) to set the request header?

1 Answers1

0

If I'm interpreting the library correctly, XMLHttpRequest isn't used directly by $script.js. It appears to be creating <script></script> tags dynamically and letting the browser handle downloading the script files. Using this library, it does not appear you can specify custom headers.

Altering the request headers the browser sends via Javascript is not possible according to some of the articles I've read including the answer to this question on SO: Is it possible to alter http request's header using javascript?

If you want to set custom headers, you'll need to use a dynamic loading library which uses XHR to load the scripts. Here is another article I've found with patterns for this type of functionality: On-Demand Javascript.

Community
  • 1
  • 1
Bradley M Handy
  • 603
  • 6
  • 15
  • 2
    I tried looking at requirejs to see if there is a way to specify custom headers for loading script dependencies. I did not see anything in the documentation. – Bradley M Handy Jun 01 '14 at 13:02
  • Thanks for your research. I updated my question slightly based on your comments. Not sure what I can do at this stage. I hope someone has faced the same problem and come up with some solution. –  Jun 01 '14 at 13:50