Solved

Adding javascrit files dynamically

Posted on 2008-11-02
1
161 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
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…

705 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