Undefined javascript function after $.getScript('');

Asked

Viewed 74 times

0

I need to load a file . js after an ajax call. I have been searching and found the $.getScript('') to call my file, it opens, everything is fine, but the functions defined in that file are not being found.

I have a clicklistener function defined like this:

var record = $('#record');

record.onclick = function () {

            startTimer(1);
            mediaRecorder.start(50);
            console.log("recorder started");

        }

when I click on the button with the id record nothing happens. I’ve tried to put a name to this function and call it on the button:

<button type="button" onclick="javascript:startRecord();" id="record">Record</button>

but it was also not recognized. What is the correct technique to do what I want?

Note: I don’t just put the script on the page (before ajax call) because I need DOM values and elements that result from this call. I am working on MVC, the ajax call is in a razorView returns html resulting from a controller

  • Maybe you should transport the bind to the "done" or Success of getScript.

  • The solution was strange. I put document.querySelector('#record'); instead of $('#record');. We noticed that the returned object was different according to each type of 'selector'. Can anyone explain the difference? I asked a question here: https://answall.com/questions/258737/qual-%C3%A9-a-difference%C3%A7a-entre-id-e-document-queryselectorid

1 answer

0

It seems to me that you are not grantindo that the script was loaded and or are forgetting to initialize something, if it is only the first case this should solve:

  <button type="button" id="record">Record</button>

Bind in $.Getscript done event('')

    $.getScript( "seu_script.js" )
    .done(function( script, textStatus ) 
     {
       $('#record').click(function(){
        mediaRecorder.start(50);
        console.log("recorder started");
       });
     });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.