loading javascript dependencies on demand

后端 未结 6 1621
灰色年华
灰色年华 2020-12-14 23:15

I\'m sure there are different approaches to this problem, and I can think of some. But I\'d like to hear other people\'s opinion on this. To be more specific I\'ve built a w

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 00:00

    function loadJSInclude(scriptPath, callback)
    {
        var scriptNode = document.createElement('SCRIPT');
        scriptNode.type = 'text/javascript';
        scriptNode.src = scriptPath;
    
        var headNode = document.getElementsByTagName('HEAD');
        if (headNode[0] != null)
            headNode[0].appendChild(scriptNode);
    
        if (callback != null)    
        {
            scriptNode.onreadystagechange = callback;            
            scriptNode.onload = callback;
        }
    }
    

    And to use (I used swfObject as an example):

    var callbackMethod = function ()
    {
        // Code to do after loading swfObject
    }
    
    // Include SWFObject if its needed
    if (typeof(SWFObject) == 'undefined')    
        loadJSInclude('/js/swfObject.js', callbackMethod);
    else
        callbackMethod();
    

提交回复
热议问题