如何添加javascript文件只有一次

how to add javascript file only one time

本文关键字:一次 javascript 何添加 添加 文件      更新时间:2023-09-26

我正在MVC应用程序上工作。我有一个母版,它正在调用外部javascript文件,有时子页面也调用javascript文件。我想如果有一次它是由子页面或母版页添加,它不应该再次添加该Javascript文件。请帮助我这个我已经做了,但不工作在这里输入代码

    $(document).ready(function () {
        var fileref1 = document.createElement('script')
        fileref1.type = "text/javascript";
        fileref1.src = "~/Scripts/testZoomPlugin.js";
        fileref1.Id = "testZoomJS";
        if (typeof fileref1 == "undefined") {
            $.getScript('~/Scripts/testZoomPlugin.js');
        }
        fileref1.src = "~/Scripts/jquery.ui.widget.min.js";
        fileref1.Id = "testWidget";
        if (typeof fileref1 == "undefined") {
            $.getScript('~/Scripts/jquery.ui.widget.min.js');
        }
        fileref1.src = "~/Scripts/jquery.ui.slider.min.js";
        fileref1.Id = "testSlider";
        if (typeof fileref1 == "undefined"){
            $.getScript('~/Scripts/jquery.ui.slider.min.js');
        }
        if(typeof fileref1=="undefined"){
            $.getScript('~/Scripts/jquery.ui.slider.min.js');
    });

只需使用RequireJS,它会做你需要的,并有一个直接的语法,在你的情况下,它将是这样的:

<script src="~/Scripts/require.js"></script>
<script>
var modules = [], prefix = "~/Scripts/";
modules.push( prefix + "testZoomPlugin.js" );
modules.push( prefix + "jquery.ui.widget.min.js" );
    require( modules, function( someModule ) {
        //This function will be called when all the dependencies
        //listed above are loaded. Note that this function could
        //be called before the page is loaded.
        //This callback is optional.
    });
</script>

为什么不把这些文件放到你的主页上呢?然后您的子页面就可以访问它们。

我不确定做这些检查是否有很多价值,如果文件被下载了一次,它将不会在子页面上再次下载,因为它将存在于缓存中。

还是我遗漏了什么?

我认为你可能是在反着做这件事。在这种情况下,您通常希望让子页面检查正在设置的某个变量,以查看它是否应该加载javascript文件。例如:你可以让一个子页面的ready函数看起来像这样:

$(function() {
  if( typeof $.fn.slider == 'undefined' )
    $('body').append('<script type="text/javascript" src="~/Scripts/jquery.ui.slider.min.js"></script>');
});

之类的

你的模块加载函数应该缓存所有模块名,以防止它们被调用两次。如果你当前的函数还不能做到这一点,那就做一个包装器。

var modules_loaded = {};
function caching_get_script(name){
    if(modules_loaded[name]) return;
    modules_loaded[name] = true;
    $.getScript(name)
}