Loading scripts dynamically

后端 未结 5 1635
青春惊慌失措
青春惊慌失措 2020-12-09 23:35

I\'m loading a few YUI scripts dynamically in my code in response to an Ajax request. The DOM and the page is fully loaded when the request is made - it\'s a response for an

5条回答
  •  情书的邮戳
    2020-12-10 00:12

    If you are loading multiple individual script files from the Yahoo! CDN, you'll need to makes sure both are loaded before executing your dependent code. You can avoid this using the combo handler. See the Configurator to get what the script url should be to load both/all needed YUI files from one url.

    http://developer.yahoo.com/yui/articles/hosting/

    With that in mind, assuming you must load the YUI files asynchronously, you should use an onload/onreadystatechange handler as noted by digitalFresh.

    I would recommend the following pattern, however:

    (function (d) {
        var s = d.createElement('script'),
            onEvent = ('onreadystatechange' in s) ? 'onreadystatechange' : 'onload';
    
        s[onEvent] = function () {
            if (("loaded,complete").indexOf(this.readyState || "loaded") > -1) {
                s[onEvent] = null;
    
                // Call your code here
                YAHOO.util.Dom.get('x').innerHTML = "Loaded";
            }
        };
    
        // Set the src to the combo script url, e.g.
        s.src = "http://yui.yahooapis.com/combo?2.8.1/...";
    
        d.getElementsByTagName('head')[0].appendChild(s);
    })(document);
    

提交回复
热议问题