出于某种原因,我使用“ append”(例如)在head标签上加载了CSS和脚本。

$("head").append('<script type="application/javascript" src="core/js/main.js"></script>');


我正在异步提取html内容(“ ajax方式”),由于内容具有特定的样式和所需的脚本功能,这就是为什么我将脚本和css与之一起加载的原因。

这是我的代码(请参阅下文)

$.ajax({
    url : 'page_loader.php',
    dataType: 'html',
    data : { page_name : 'test' },
    type: 'get',
    beforeSend : function(){
        //show a spinner
        $("#spinner").show();
    },
    success : function(data){
        //before load contents, load the css first
        $("head").append('<link rel="stylesheet" type="text/css" href="core/css/main.css" />');
        //load the pulled html contents to the div that has an id of ajax_page
        $("#ajax_page").html(data);
        //then load the script on the head
        $("head").append('<script type="application/javascript" src="core/js/main.js"></script>');
        //hide the spinner
        $("#spinner").hide();
    }
});


一切正常,但是我不希望脚本和链接在每次内容加载时都重复或成倍增加,因为您可以看到我正在使用append,因此每次调用ajax函数时,都会将脚本和css附加在head标签上也是重复的(假设ajax函数被调用两次或多次),所以现在我想要防止它发生,有没有一种方法叫我加载一次?还是可以多次加载(ajax运行多次)可以吗?

PS:我想做的事就像在链接和脚本上放置一个ID,以便我可以检查它是否确实存在,如果存在,则不要加载,否则,请加载它。那么将ID放在链接标签或脚本标签上是有效的吗?

最佳答案

jQuery具有可用于JS文件的getScript功能。

说明:使用GET HTTP请求从服务器加载JavaScript文件,然后执行它。

jQuery.getScript(
    url,
    function(data, textStatus, jqxhr) {

    });


阅读材料:

getScript

10-08 03:12