How do I load an external file and make sure that it runs first in JSFiddle?

Deeptechtons picture Deeptechtons · Jan 9, 2012 · Viewed 27.7k times · Source

I have a JsFiddle here, and added Microsoft AJAX to be loaded through external JS/resource section. How can I tell whether or not my JS code is run after the AJAX file has finished loading?

Seems that the AJAX does not load either. :(

Here is the code in the JSFiddle:

Type.registerNamespace("Tutorial.Chapter1");
Tutorial.Chapter1.Person = function(firstName, lastName) {
    this._firstName = firstName;
    this._lastName = lastName;
};
Tutorial.Chapter1.Person.prototype = {
        set_firstName: function(value) {
            this._firstName = value;
        },
        get_firstName: function() {
            return this._firstName;
        },
        set_lastName: function(value) {
            this._lastName = value;
        },
        get_lastName: function() {
            return this._lastName;
        },
        _firstName: "",
        _lastName: "",
        displayName: function() {
            alert("Hi! " + this._firstName + " " + this._lastName);
        }
    };
Tutorial.Chapter1.Person.registerClass("Tutorial.Chapter1.Person", null);

Answer

Jpsy picture Jpsy · Mar 26, 2013

The External Resources tab of jsFiddle is currently somewhat tricky and unstable to use. The resources defined here are often not correctly included into the code. There seems to be an issue with the automatic recognition of JS and CSS resources. If this happens, the external resource is simply not added to the head section of the resulting code. You can check that by reviewing the source code of the Result frame of your jsFiddle. You will find that your MS AJAX resource is simply NOT mentioned in the resulting HTML code.

The correct recognition can actually be forced by adding a dummy value to the resource's URL like this (see –>jsFiddle docs for more info):

...&dummy=.js

Here is an example that shows how to add the external Google Maps API resource to a jsFiddle (mind the dummy parameter at the very end!):

https://maps.googleapis.com/maps/api/js?sensor=false&dummy=.js

Unfortunately this won't work for you as the MS AJAX URL will fail when additional parameters are appended.

A solution (and currently the safest way to load external resources) is to avoid the External Resources tab altogether and load external code manually in the first line(s) of jsFiddle's HTML window like this:

<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/3.5/MicrosoftAjax.js"></script>

Here is your jsFiddle modified to use that method: http://jsfiddle.net/rEzW5/12/

It actually does not do a lot (I did not check what is wrong with the rest of your code), but at least it does not throw JavaScript errors anymore.