is it possible to load js files dynamically via ajax

Posted on 2009-02-17
Last Modified: 2013-11-19
so I've got an html page.  I'm using some YUI scripts and using some ajax within the page.  I basically don't want to load the js files until they're needed so I was wondering if there were a way where if somebody clicked a link it could fire something that would load another javascript file in the page?

So for example some YUI library is needed for a function to execute well is it possible to include that library if the library if it wasn't included in the html when the page loaded?
Question by:ICPooreman
    LVL 5

    Expert Comment


    Never tried it, but I wonder if you could simply append a script tag node to the DOM, with it's source set.  I know that you can do the same with an image, and get it to load when its attached to the document.

    LVL 41

    Expert Comment

    I agree with null.  That is what I would try.

    Note however, that you would want syntactically correct javascript.

    Author Comment

    ya I've been reading up on it.  It appears that you can do what you're stating but you have to be careful with different browser implementations.

    I've come across the fact that YUI has a loader utility that might be able to do what I need I'm looking into that but appreciate any other comments people have.
    LVL 16

    Accepted Solution

    You can load a js file dynamically. For that you dont need ajax. Just simple javascript will do the trick,

    this loads a javascript dynamicaly

    var exScript = document.createElement('script');
    var headTag = document.getElementsByTagName('head')[0];

    check this also

    hope these helps,

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    Shoutout to Emily Plummer ( for giving me this article! She did most of it, I just finished it up and posted it for her :)    Introduction In a previous article (http://www.experts-exchang…
    Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL ( several years ago, it seemed like now was a good time to updat…
    The viewer will learn how to dynamically set the form action using jQuery.
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now