Dynamically loading javascript source from a string into the DOM using Jquery

Status
You're currently viewing only stodge's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

stodge

Ars Tribunus Militum
1,907
I'm experimenting with dynamic loading of javascript using JQuery. So basically I have a loadScript function that accepts either the URL of a JS file or a javascript source in a string.

For the former, I create a 'script' element, set its src attribute to the URL of the file and insert the element into the DOM's head element. So far it seems to work nicely.

For the latter, I create a 'script' element, set its innerHTML to the JS string and insert it into the DOM's head element. This doesn't work so well. I *think* it's because the JS source in question contains:

$(document).ready(function() {
// put all your jQuery goodness in here.
});

It looks like the JS source in my string is stomping over parts of the DOM it shouldn't and changing existing elements.

Is the latter possible? Is my approach completely wrong?

Thanks
 

stodge

Ars Tribunus Militum
1,907
Basically I have a desktop like environment (yes I know but bear with me, the web application in question would benefit greatly from this design) with multiple HTML/CSS dialogs. A dialog is created and its contents is populated from an existing HTML page on the server. The code intercepts a mouse click on a link in the dialog and JQuery requests the requested page from the server.

The code then parses the request, creates a list of script, style and link tags and then removes the header contents and body tags. The remaining content is stored in the dialog's content DIV.

Each script elements is processed. Script elements with a 'src' attribute are added to the DOM's head. I'm having trouble inserting script elements with no 'src' attribute. These elements contain inline javascript so I thought I could create a script element, set its innerHTML (or appropriate attribute) to contain the JS source and add it to the DOM. But this is the part that isn't working.
 
Status
You're currently viewing only stodge's posts. Click here to go back to viewing the entire thread.
Not open for further replies.