views:

24

answers:

3

Hi

My site operates on an ajax "framework". Whenever a user opens a new page, that page loads in the necessary css and js files to view the page properly and adds them to the current document. The js files are loaded like this in jQuery:

function getJS(jsfiles) {
    $.each(jsfiles, function(i, val) {
        $.getScript(val);
    });
}

My problem is that whenever a js-file is loaded, that file is added to the document permanently and operates across all ajax "sub-sites". Therefore I get problems with reserved function names, functions that requires certain DOM-elements to be present when executed and throws an error otherwise, etc. etc. Is there a way to remove these files from the document again?

A: 

You can try to do something like this

$('head').empty();
$('head').append('<script src="yourscript.js" type="text/javascript" />');

Hope this helps

chermosillo
This would require me to load all my javascript files everytime i load a new ajax-page. It isn't very efficient.
soren.qvist
It will also remove everything in the `<head>` element, including stylesheets. I could be wrong; but my guess is that some browsers will trigger a re-draw when the DOM changes, and all styling on the markup will get removed.
roosteronacid
+1  A: 

You could scope the contents of the JavaScript files you are loading, using a self-executing function. Or try assigning an ID to the script-blocks and remove them by doing: $("id of the script block").remove();.

roosteronacid
Thanks. I'll try both of your solutions.
soren.qvist
+1  A: 

I don't know how jQuery attaches new scripts, but you could do an AJAX request and build your own script elements in the callback, giving them a class that can be selected later for removal.

$.ajax({
    url:'test.js',
    dataType: 'text',
    success: function(script) {
        var head = document.getElementsByTagName('head')[0];
        var scr_elem = document.createElement('script');
        scr_elem.setAttribute("class","new_script");
        scr_elem.setAttribute("className","new_script");
        scr_elem.type="text/javascript";
        scr_elem.appendChild(document.createTextNode(script));
        head.appendChild(scr_elem);
    }
});

// Later on
$('.new_script').remove();

Note that I've only tested this in Webkit and Firefox.

patrick dw
Thanks, interesting solution. I think I'll go through the jQuery source and see if it's anything like this.
soren.qvist
@soren - For some reason I had trouble creating a script element in the typical jQuery way. And I didn't see any attached scripts in the DOM when letting jQuery attach them. That's why I resorted to the DOM API. You could try getting rid of the `.setAttribute()` calls and just doing `scr_elem.className = "new_script"`, but you should do some cross-browser testing if so.
patrick dw