简体   繁体   English

如何动态加载位于外部服务器中的javascript文件?

[英]How do I load javascript file that's located in external server dynamically?

I am trying to load a javascript file that's stored in an external server.I tried using plain js to do so in the following manner: 我正在尝试加载存储在外部服务器中的javascript文件。我尝试使用普通js通过以下方式进行加载:

$(document).ready(function(){
    scriptObject = document.createElement('script');
    scriptObject.type = 'text/javascript';
    scriptObject.async = true;
    scriptObject.src="https://seal.verisign.com/getseal?host_name=esewa.com.np&size=S&use_flash=YES&use_transparent=YES&lang=en",
});

$(window).load(function(){
                document.getElementByTagName('head')[0].appendChild(scriptObject);      
            });

Since Js is single threaded and the file loading procEss took a lot of time i tried using ajax and js to do so in the following manner 由于Js是单线程的,并且文件加载procEss花了很多时间,因此我尝试使用ajax和js通过以下方式进行操作

$(document).ready(function(){
    scriptObject = document.createElement('script');
    scriptObject.type = 'text/javascript';
    scriptObject.async = true;
    $.ajax({
        type: "GET",
        url:"https://seal.verisign.com/getseal?host_name=esewa.com.np&size=S&use_flash=YES&use_transparent=YES&lang=en",
        dataType: "script",
        success: function(data) {
            scriptObject.src= data ;
            $(window).load(function(){
           document.getElementByTagName('head')[0].appendChild(scriptObject);   
            });
        }
    }); 

});

However I am not sure if one can load .js file in the way that i have done with ajax and jquery. 但是我不确定是否可以像使用ajax和jquery一样加载.js文件。 Is there a better way for doing this? 有更好的方法吗? Any help would be appreciated. 任何帮助,将不胜感激。

对于该http://api.jquery.com/jquery.getscript/,已经存在出色的jQuery函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM