Question

I have a menu with say 5 buttons. On each item click, I want to AJAX load a HTML file that contains some script. The loaded file looks like the following:

<div>
  someContent...
</div>
<script>
FileScriptObject = {
  init: function() {
  },

  cleanup: function() {
  },
};
</script>

I want to be able to $("#someDiv").load("externalFile.html"); and somehow, get hold of that FileScriptObject. Is it possible?

No correct solution

OTHER TIPS

There is a jQuery function for that:

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

If I understand your question, then I think you are interested in loading a new script file dynamically. This is entirely possible; for example if I wanted to load a js file called newScript.js then I can create a script tag <script type="text/javascript" src="newScript.js"></script> and add it to the header. To do this I can do the following:

var head = document.getElementByTagName("head")[0];
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.onreadystatechange = function() {
    if(this.readystate == "complete") {
        // Script loaded
    }
}
newScript.src = "newScript.js";
newScript.onload = function() {
    // Script loaded
}
head.appendChild(newScript);

Note that there are two different load handlers, this is because the readystate check is for IE and onload is for others.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top