简体   繁体   English

如何使用html加载外部js文件

[英]How to load external js files with html

I have use following method to load html content to my index, 我使用以下方法将html内容加载到索引中,

$("#home-btn").click(function() {
    $("#content").load("views/plant.html");   
});

It's loading the html contents correctly, but i have used some external js files that related to the html 's and link the related external js files to my index html . 它加载html正确的内容,但我已经使用了一些外部js是相关文件html的和相关的外部链接js文件到我的索引html Issue is, missing the effects form external js in the html contents that i have load. 问题是,我加载的html内容缺少来自外部js的效果。 How can I fix it? 我该如何解决?

Refer your external js file with your html file as you see in the below code. 如下面的代码所示,将您的外部js文件与html文件一起引用。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="Scripts/externalFile.js"></script>       
</head>
<body>
</body>
</html>

Load jQuery 加载jQuery

$("#home-btn").one( "click", function() {
    console.log("You'll only see this once!");

    sendMyAjax('http://yoursite.com/script1.js');
    sendMyAjax('http://yoursite.com/script2.js');
    sendMyAjax('http://yoursite.com/script3.js');
});

function sendMyAjax(URL_address) {
    $.ajax({
        url: URL_address,
        dataType: 'script',
        cache: true, // or get new, fresh copy on every page load
        success: function() {
            // Callback
        }
    }
}

By this method the extra script will only be loaded after your click on specified location. 通过这种方法,只有在单击指定位置后,才会加载额外的脚本。 By this way the load required to load extra JS on time of first page load can be avoided. 通过这种方式,可以避免在首页加载时加载额外的JS所需的负载。

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

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