在JS内动态加载JS我有一个动态网页,需要导入外部JS文件(在IF条件)在另一个javascript文件中。我试图寻找一个可行的解决方案,但没有奏效。我尝试使用以下方法将JS文件加载到DOM中document.createElement()但也没用。显然,Js被加载到DOM中,但在当前的JS文件中无法访问。jquery中的解决方案也很好。
3 回答
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
$.getScript()
jQuery.loadScript = function (url, callback) { jQuery.ajax({ url: url, dataType: 'script', success: callback, async: true });}
if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){ //Stuff to do after someScript has loaded});
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
var script = document.createElement('script');script.src = something;//do stuff with the script
load
var script = document.createElement('script');script.onload = function () { //do stuff with the script};script.src = something;document.head.appendChild(script); //or something of the likes
慕村9548890
TA贡献1884条经验 获得超4个赞
var loadJS = function(url, implementationCode, location){ //url is URL of external file, implementationCode is the code //to be called from the file, location is the location to //insert the <script> element var scriptTag = document.createElement('script'); scriptTag.src = url; scriptTag.onload = implementationCode; scriptTag.onreadystatechange = implementationCode; location.appendChild(scriptTag);};var yourCodeToBeCalled = function() {//your code goes here}loadJS('yourcode.js', yourCodeToBeCalled, document.body);
添加回答
举报
0/150
提交
取消