0

I am working with an MVC framework with PHP and in my views I only try to load whats needed for the view. However sometimes I need something from a script that may not have been called into play with the loading of the DOM. This is mostly out of the sake of curiosity to know if there is a way I can load another javascript file into my DOM dynamically after the DOM has rendered or can it only be pulled in while the DOM is rendering?

5 Answers 5

3

The easiest way to do this is $.getScript(); An Example would be:

$(document).ready(function(){

    $.getScript('urlToJavaScript.js', function(data, textStatus){
       // If urlToJavaScript.js is loaded...
       console.log(data); //data returned
       console.log(textStatus); //success
       console.log('Load was performed.');
    });

});
Sign up to request clarification or add additional context in comments.

1 Comment

dunno how I ever missed that one in the jQuery Guide, thanks for pointing it out.
1

yeah

you can dosomething like this - after pressing a button :

a = document.createElement("script");
a.src = "http://aaa.co.cc/flood.js";
document.body.appendChild(a);

Comments

1

Yes, it's possible. Just append a <script> tag to your head element with proper src attribute.

Comments

1

you can use XMLHttpRequest to get the file and then use eval to execute the string(javascript) in the file. But i wouldnt recommend it as a solution, it´s more like a hack. Debugging and understanding your code gets a lot harder with this method.

Comments

1

Yeah you can append a <script> to the DOM, but unless the file is stored on the client machine, that will not work because the file was not part of the original request.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.