Olof
Olof

Reputation: 797

Dynamically added javascript not running

I'm building a website that is heavily built on ajax. Some of my JS comes as part of the pages that I load through ajax. The functions from the JS cannot be called from other JS scripts that has been loaded earlier. As I have understand it, it has to with the code not being really declared and that I could use eval() on the code. But that feels like waste of resources since the code runs and works aslong it don't need to work with code that is already declared.

My little short ajax page loader.

$(document).ready(function(){
    var old = "home"
    $("#topMenu a").on("click",function(){
        if(typeof edit_menu !== 'undefined' && edit_menu){
            return;
        }
        var link = $(this).attr("data-link");
        //Load Ajax
        LoadPage(link, old);
    });
});

function LoadPage(link, old){
    $.ajax({
        url: "pages/" + link + ".php",
    }).done(function(data){
        $("#content").html(data);
    });
    Hide();
    history.pushState(old,null,"?page=" + link);
}

If I login as admin I will then also have an admin JS file loaded as part of the DOM. The script calls a function in another JS file thats is loaded dynamically. The function doesn't run because the admin JS file is not aware of the new funciton.

The dynamically added JS file is a script tag part of other HTML code. Example of dynamically added code.

    <script src="/javascript/projects.js"></script>
    <header>Projects</header>

<article>
    <h1>First project</h1>
    <section class="summary">
Lorem ipsum is da shit
    </section>
    <section class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam orci, hendrerit a justo sit amet, egestas ullamcorper orci. Aliquam quis facilisis urna. Fusce blandit pellentesque elit. Vivamus ullamcorper luctus felis in rutrum. Nam quis facilisis mauris. Nunc iaculis sagittis sollicitudin. Ut imperdiet, purus et fermentum tempor, leo mauris feugiat libero, eu pulvinar odio felis sed tortor. Mauris vel libero orci. Suspendisse a mollis turpis. Maecenas egestas felis eget ultrices porta. Nulla non metus ut augue faucibus ultrices. Phasellus arcu magna, vulputate eget sollicitudin a, ullamcorper a ipsum. Suspendisse potenti. Pellentesque eget vulputate ipsum.</p>             <p>Ut ultricies faucibus sapien, ut sodales turpis rhoncus molestie. Vivamus luctus auctor pellentesque. Phasellus ut ex vulputate, congue felis nec, pharetra odio. Ut ligula ante, luctus nec enim ac, lobortis ultrices elit. Quisque sed justo a nibh congue tempor sit amet ut mauris. In non enim nulla. Nulla et dolor sollicitudin, finibus ante eu, egestas purus. Phasellus sit amet eros dignissim, pellentesque elit tempor, sagittis eros. Donec sollicitudin velit ipsum, semper ultrices sapien blandit non. Phasellus vehicula orci in ipsum blandit hendrerit. Vestibulum facilisis dolor ac tincidunt fermentum.</p>
    </section>
    <span>Update text</span> <input type="checkbox" class="update_projects" data-id="First project" /><br /><button class="update_text">Update</button><input type="hidden" class="token" value="4926dd431992894a8364ca4d89733038be0cb0ec4897eb2a417637685554b6df40149522a858b5bfaaa91526b84718cdd54b301229371841dc2f022bbd0f804eaf31abb51caef55b26cca3209cc3b0838f194176f78f0931b2217669cd2912faa25a3c3e469ce686d79ac7a7852fbfee9d6d4dc5da18b499e703b4ef57fc88c1a99ccf8943af5853433f911ce276ff13e9ecbfb074d747f1a07f26c141f80383a149902dfe7469262724e2f67aae48d9919d486855a892b17681660ab3e0d25f98e714c3d98cc903" /><input type="hidden" class="id" value="1" /><br /><input type="text" name="tag" class="tag" value="php" />
</article><article>
    <h1>Secons project</h1>
    <section class="summary">
And I'm not lying
    </section>
    <section class="text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam orci, hendrerit a justo sit amet, egestas ullamcorper orci. Aliquam quis facilisis urna. Fusce blandit pellentesque elit. Vivamus ullamcorper luctus felis in rutrum. Nam quis facilisis mauris. Nunc iaculis sagittis sollicitudin. Ut imperdiet, purus et fermentum tempor, leo mauris feugiat libero, eu pulvinar odio felis sed tortor. Mauris vel libero orci. Suspendisse a mollis turpis. Maecenas egestas felis eget ultrices porta. Nulla non metus ut augue faucibus ultrices. Phasellus arcu magna, vulputate eget sollicitudin a, ullamcorper a ipsum. Suspendisse potenti. Pellentesque eget vulputate ipsum.</p>
            <p>Ut ultricies faucibus sapien, ut sodales turpis rhoncus molestie. Vivamus luctus auctor pellentesque. Phasellus ut ex vulputate, congue felis nec, pharetra odio. Ut ligula ante, luctus nec enim ac, lobortis ultrices elit. Quisque sed justo a nibh congue tempor sit amet ut mauris. In non enim nulla. Nulla et dolor sollicitudin, finibus ante eu, egestas purus. Phasellus sit amet eros dignissim, pellentesque elit tempor, sagittis eros. Donec sollicitudin velit ipsum, semper ultrices sapien blandit non. Phasellus vehicula orci in ipsum blandit hendrerit. Vestibulum facilisis dolor ac tincidunt fermentum.</p>
    </section>
    <span>Update text</span> <input type="checkbox" class="update_projects" data-id="Secons project" /><br /><button class="update_text">Update</button><input type="hidden" class="token" value="4926dd431992894a8364ca4d89733038be0cb0ec4897eb2a417637685554b6df40149522a858b5bfaaa91526b84718cdd54b301229371841dc2f022bbd0f804eaf31abb51caef55b26cca3209cc3b0838f194176f78f0931b2217669cd2912faa25a3c3e469ce686d79ac7a7852fbfee9d6d4dc5da18b499e703b4ef57fc88c1a99ccf8943af5853433f911ce276ff13e9ecbfb074d747f1a07f26c141f80383a149902dfe7469262724e2f67aae48d9919d486855a892b17681660ab3e0d25f98e714c3d98cc903" /><input type="hidden" class="id" value="2" /><br /><input type="text" name="tag" class="tag" value="" />
</article></section>

UPDATE After some more testing I have found the JS can't find any of my added HTML while the js added on the same time can.

Upvotes: 0

Views: 295

Answers (3)

Nadeem Manzoor
Nadeem Manzoor

Reputation: 750

Try the following script, this will remove the script from the loaded HTML and load them on to the page before adding the content. Also it makes sure that the same javascript file does not get added multiple times.

function LoadPage(link, old){
    $.ajax({
        url: "pages/" + link + ".php",
    }).done(function(data){
        $loadedData = $("<div>"+data+"</div>");
        $loadedData.find('script[src]').each(function(i,v){
            var jsPath = $(this).attr('src');
            if($('[src="'+jsPath+'"]').length == 0){
               var tag = document.createElement('script');
               tag.src = jsPath;
               var firstScriptTag = document.getElementsByTagName('script')[0];
               firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            }
        });
        $loadedData.find('script[src]').remove(); 
        $("#content").html($loadedData.html());
    });
    Hide();
    history.pushState(old,null,"?page=" + link);
}

Upvotes: 0

ClementNerma
ClementNerma

Reputation: 1109

To load the script you must append it as an HTML element, like this :

}).done(function(data) {
    var el = $(document.createElement('div')).html(data);
    var scripts = el.find('script');

    for(var i = 0; i < scripts.length; i++) {
        window.eval(scripts[i].innerHTML);
        scripts[i].remove();
    }

    $('#content').html(el.html());
});

Upvotes: 0

nazimboudeffa
nazimboudeffa

Reputation: 979

I am trying to understand the question but as i can't comment for the moment some parts of it are not enugh clear, i work with jsfiddle if it can help, is it possible to make a little example not all the code to help me understand what's going on. Starting with this function for example :

function LoadPage(link, old){
    $.ajax({
        url: "pages/" + link + ".php",
    }).done(function(data){
        $("#content").html(data);
    });
    Hide();
    history.pushState(old,null,"?page=" + link);
}

https://jsfiddle.net/3z62n8c2/

Upvotes: 1

Related Questions