且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

脚本标记中的HTML中的Dynamic Src

更新时间:2023-12-05 20:35:22

这是动态加载javascript的调用:

This is call dynamically loading javascript:

var script = document.createElement('script');
script.setAttribute( 'src', 'socket.io.js');
document.head.appendChild(script);
//script that use socket.io

但是,当脚本完全加载时,您还不知道另一个问题.如果您调用的函数是在加载前在外部脚本中定义的,那就是错误的!

But there's another problem that you don't know when the script is fully loaded. If you call a function is defined in external script before it's loaded, it's error!

var script = document.createElement('script');
script.onload = function () {
    //script that use socket.io
};
script.setAttribute( 'src', 'socket.io.js');
document.head.appendChild(script);

我们可以创建一个实用函数:

And we can make a utility function:

function loadScript(scriptPath, callback) {
    var script= document.createElement('script');
    script.setAttribute('src', scriptPath);
    script.onload = callback();
    document.head.appendChild(s);
};

loadScript('socket.io.js', function() {
    //script that use socket.io
});

或者您可以使用jQuery $ .getScript():

OR you can use jQuery $.getScript():

$.getScript('socket.io.js', function(data, textStatus, jqxhr) {
    //script that use socket.io
});

有关更多信息: https://api.jquery.com/jquery.getscript/

PS:使用您的代码,将像这样:

PS: with your code, it will be like this:

<!DOCTYPE html>
    <html>
    <head>
        <title>SAMPLE</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script id="script" src=""></script>
        <!--<script type="text/javascript">-->
            <!--document.getElementById("script").src = "https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js";-->
        <!--</script>-->
        <!--<link rel="stylesheet" href="/styles.css">-->
    </head>
    <body bgcolor="#ffffff">
    <table id="table" border=1>
        <thead>
        <th><center>Sample</center></th>
        <th></th>
        </thead>
        <tbody id="online"></tbody>
    </table>
    <script>
        var script = document.createElement('script');
        script.onload = function () {
            var ipServer = location.host;
            var socket = io.connect('ws://' + ipServer);
        };
        script.setAttribute( 'src', 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js');
        document.head.appendChild(script);
    </script>
    </body>
    </html>