动态导入JavaScript [英] Dynamically Importing JavaScript

查看:50
本文介绍了动态导入JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问将JavaScript(.js)文件动态导入到父JavaScript代码中的正确方法是什么?

What is the correct way to dynamically import JavaScript (.js) files into a parent JavaScript code, please?

我正在使用以下代码,但似乎不正确:

I am using the following code, but it seems not correct:

    function loadjscssfile(filename, filetype)
{
    //if filename is a external JavaScript file
    if (filetype=="js")
    {
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    }
    //if filename is an external CSS file
    else if (filetype=="css")
    {
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref!="undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref)
}

我认为代码是不正确的,因为在主JavaScript代码中,我无法读取导入代码中定义的变量,例如:

I think, the code is not correct, because, in the master JavaScript code, I can no read variables defined in the imported code, such as:

var fileRef = loadjscssfile('Language/svk.js', 'js');
alert("Pet Name: " + PETNAME);

导入的svk.js文件包含唯一的代码:

imported svk.js file contains the only code:

// JavaScript Document
var PETNAME = "Beauty";

谢谢.

推荐答案

您无法读取 PETNAME 变量的原因是,像这样动态注入脚本是异步且非阻塞的.这意味着您的 alert 会在实际加载脚本之前执行.相反,您可能必须轮询 PETNAME 变量的存在:

The reason you can't read the PETNAME variable is that dynamically injecting scripts like this is asynchronous and non-blocking. This means that your alert executes before the script has actually been loaded. Instead, you might have to poll for the existence of the PETNAME variable:

var waitForPETNAME = function(){
        if (typeof PETNAME === 'undefined') {
            setTimeout(waitForPETNAME, 15);
        } else {
            // execute code that uses PETNAME
        }
    };

waitForPETNAME();

此外,动态注入元素的更简单的方法是将它们插入第一个脚本元素之前,因为您可以确定必须存在一个脚本元素(否则就不会执行代码).换句话说,替换为:

Also, a more fool-proof way to inject elements dynamically is to insert them before the first script element since you know for sure that a script element has to exist (otherwise you wouldn't be executing code). In other words, replace:

document.getElementsByTagName("head")[0].appendChild(fileref)

具有:

var insref = document.getElementsByTagName('script')[0];
insref.parentNode.insertBefore(fileref, insref);

这篇关于动态导入JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆