Solved

Adding javascrit files dynamically

Posted on 2008-11-02
1
162 Views
Last Modified: 2012-08-13
I came across the following example which uses AJAX callbacks to register javascript files on the fly.

http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

It seems to sort-of work or maybe it works perfectly and I just don't fully understand it. Here's my problem...

Under the heading of "Adding Javascript Through AJAX", the line "After this is done the functions and variables will be available to the other functions in your web page" appears at the end of the paragraph just before the code sample (which I copied and pasted into my project). I assumed that I'd be able to call functions within the file called "test.js" from anywhere else on my page after the file has been loaded. However this does not seem to be the case. I'm failing to understand what's wrong here. Button2 calls the function "foo();" which is just an alert box saying "hello" but it doesn't find the object even after I click Button1. I know the registerNewScript() function works because the test.js file has an alert message as the first argument and the alert DOES pop up when I click it. Can anyone offer advice on this? Perhaps this isn't the best way to load an external javascript file dynamically? Other suggestions are welcome.
<script language="javascript" type="text/javascript">

    function registerNewScript()

    {

        var getScriptViaAjax = new ajaxObject("http://localhost:49863/js/test/test.js", attachScript);

        getScriptViaAjax.update();

    }

</script>
 

...
 

        <input id="Button1" type="button" value="button" onclick="registerNewScript();" />

        <input id="Button2" type="button" value="foo" onclick="foo();" />
 

/*****************************/

/* THE ENTIRE FILE "test.js" */

/*****************************/

alert("Found me!");
 

function foo()

{

    alert("foo!");

}

Open in new window

0
Comment
Question by:Russ Suter
1 Comment
 
LVL 18

Accepted Solution

by:
wilq32 earned 500 total points
ID: 22863235
Oh man... well.. AJAX is mainly for downloading for example dynamic changed content, or content on demand. And I wouldn't use that in your position if i dont have to. Just use the first example of loading script if you really need. I have to say that I work in company as a javascript expert, and we work on about a big project with lot of javascript (more than 20 000 lines) and actually I does not found any need for AJAX script loading, except:

- some security? Javscript loaded after logged in or something? But its kinda easy to break so what for?,
- make page load only once, and get other script downloaded on need... but man javascript (obfuscated and gziped)  takes around of 20-50 kb of data... why not put everything in one file?:),

Main disadvantage of script on page you provided - they use (evil) eval :>. Using so make a new context to execute script thats inside, its very slow and if you can its better to not use it (i read some about it, i tested it in big application and ... welll.. thats true :)) ). Im just not sure how <script> tag is parsed (or created via document.createElement('script'), but I would try to make this element with .innerHTML = something taken from AJAX and then append to body. Should work :)

So (quote from page you gave):

var headID = document.getElementsByTagName("head")[0];        
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.onload=scriptLoaded;
newScript.src = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=sunset&format=json';
headID.appendChild(newScript);


just do not use  .src but just put something like this:

<body>

<Script type="text/javascript">
var a=document.createElement('script');
a.type="text/javascript";
a.innerHTML=" alert('test') "
document.body.appendChild(a);

</script>

</body>
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

919 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

21 Experts available now in Live!

Get 1:1 Help Now