1

I want to execute a callback once I load a script using pure javascript. I am able to load the script correctly, but my callback is not firing. I heard using JSONP I can do this type of stuff, however, I cannot quite get it to work. Here is my code:

function foo(){
   alert('got the data');
}

var el = document.createElement("script");
el.setAttribute("src", "//ajax.googleapis.com/ajax/libs/webfont/1.5.0/webfont.js?callback=foo");
document.body.appendChild(el);

1 Answer 1

1

JSONP has nothing to with that. The URL you are trying to load already returns JavaScript, so you need to do is bind a load event handler to the element:

var el = document.createElement("script");
el.setAttribute("src", "//ajax.googleapis.com/ajax/libs/webfont/1.5.0/webfont.js");
el.onload = function() {
    // script loaded
};
document.body.appendChild(el);

See also How do I include a JavaScript file in another JavaScript file?


JSONP is used as an alternative to Ajax when you want to load data from an external domain, but it is something the server has to support. If the server supports it, instead of returning (for example) simple JSON:

{"foo": 42}

it would wrap it in callbackName(...); to create a JS script with a single function call:

callbackName({"foo": 42});

The actual function name is taken from the GET parameter callback.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.