0

I'm trying to load in the jQuery template plugin using jQuery.getScript, but even though it does the request and the file comes in correctly (replaced the url with a test JS and the javascript does get evaluated correctly), jQuery.tmpl is still undefined but if I run jQuery.tmpl in Chrome's console, it is a function.

Example code:

<script type="text/javascript">    
jQuery.getScript('http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js');
console.log(jQuery.tmpl); // returns undefined.
</script>

Any idea what the issue might be?

7 Answers 7

3

You should wait until the script will be loaded.

jQuery.getScript('http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js',
    function(){
        console.log(jQuery.tmpl);
    }
);
1
  • At first was really surprised:)
    – bjornd
    Aug 10, 2011 at 17:45
2

Wait until it loads. Try using:

jQuery.getScript('http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js', function() {
    console.log(jQuery.tmpl);
});

or to make it more readable, try using:

$.ajax({
    url: "http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js",
    dataType: "script",
    success: function() {
        console.log(jQuery.tmpl);   
    }
});
0

You shuold use it in the callback(success handler) method of getScript

jQuery.getScript('http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js',
function(){
   console.log(jQuery.tmpl);
});
0

Your problem is that the script is loading asynchronously, which means you need to wait for it to complete before you can use it.

http://api.jquery.com/jQuery.getScript/

The solution is to have the following:

$.getScript('.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js', function (data, textStatus) {
    //Use the script now
});

I'd recommend simply adding a reference to the script on the page if you're going to need it immediately.

0

You need to wrap that in the callback as the next statement executes immediately, whereas script load may take some time.:

jQuery.getScript('http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js', function() {
   console.log(jQuery.tmpl);
});
0

I ended up just making the .ajax call sync, so that I could use it as part of my logic flow:

jQuery.ajax({
    url: script,
    async: false,
    dataType: "script",
    success: function() {
        console.log("Loaded "+script);   
    },
    complete: function() {
        console.log("Failed to load "+script);   
    }
});
0

Sync or async extension method to $.getScript: https://github.com/hudsonfoo/jquery-getscripts

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.