wannabeartist
wannabeartist

Reputation: 2833

how to load a new script in a single-page app?

I'm trying to build a single-page app that has several views (screens, page contents)

My App's UI has a permanent menu bar and a "view area" which retrieves a view via Ajax, based on menu selections. This works great for simple HTML content and keeps my menu-script running on the background despite which view is being displayed.

But what if my view needs an additional script? How do you load and execute a script as a result of a view change (=a page fragment was loaded as a result of a button click) also, how do I get rid of that script when I choose a different view?

I know I can embed a script-tag into the page fragment and write the code there, but I'm really looking for a more robust way of doing this, preferably so that an instance of an object is created when the view is loaded and then discarded when the view changes.

Upvotes: 0

Views: 2984

Answers (2)

Chris Sobolewski
Chris Sobolewski

Reputation: 12935

You can use javascript to add a <script> tag in the same way you would any other tag.

The hardest part is knowing where to place it, but if you have control over your markup, this isn't too big a barrier.

Something along these lines:

function DST(url)
{
    var s = document.createElement(’script’);
    s.type=’text/javascript’;
    s.src= url;
    document.getElementsByTagName(’head’)[0].appendChild(s);
}

If you need something to happen automatically when you load that script, you should be able to use a self executing anonymous function to do the job.

(function(){alert('this happened automatically');})();

If you need to pass anything in to the function it would look like this:

(function($){alert('this happened automatically');})(jQuery);

If you really need to discard the scripts, you can delete the nodes, but it might be better to leave them in, in case a user reactivates a view, so you don't have to make the AJAX call and associated HTTP request, allowing the page to load faster.

Upvotes: 1

newtron
newtron

Reputation: 6114

yepnope.js is a great conditional loader. You could use it to check certain conditions (e.g. view, state) before loading a script. I don't think it has the ability to remove a script that's already been loaded, though.

Upvotes: 1

Related Questions