Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
Hm, I have a potential answer for myself. I can add some script at the bottom of that loaded HTML that passed the FileScriptObject to a known registered object, that can then handle calling it. Such as window.SomeManager.executeMe(FileScriptObject); – MeshMan 7 hours ago
add comment (requires an account with 50 reputation)

2 Answers

There is a jQuery function for that:

$.ajax({
  url: url,
  dataType: "script",
  success: success
});
share|improve this answer
This doesn't tell me how I can get hold of the script object contained in the loaded HTML file. – MeshMan 7 hours ago
Why do you want to get hold of it? Are they parsed out by jQuery? – xercces 7 hours ago
When I was out these layers when selecting different menu items, I want to be able to call a "Cleanup" method on the old layer, and an "Init" when the new layer has finished loading. I think I solved it though, see my comment on the original post. – MeshMan 7 hours ago
add comment (requires an account with 50 reputation)

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.

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.