【问题标题】:Load jquery plugin js after ajax page load contentajax页面加载内容后加载jquery插件js
【发布时间】:2016-03-13 05:10:50
【问题描述】:

敌人示例,我有使用 select2 插件的页面:

function Initialize()
{
    if($('.su-tech').length) {
            $('.su-tech').select2({
                allowClear: true,
                width: '100%'
            });
    }
} 

和这样的html代码:

<select class="select2 su-tech" style="width:100%;">                                                    
    <option value="1" >option1</option>
    <option value="2" >option2</option>
    <option value="3" >option3</option>
</select>

我也使用 ajax 通过 jQuery 加载 html 内容:

    $(document).on("click", "#page1", function () {
        $.ajax({
            type: 'POST',
            url: "/example-page1",
            success: function (result) {
                $('.ajax_content').html(result);
                Initialize()
            },
        })
    })

现在我想动态加载 jscss 每个 jquery 插件:

<link rel="stylesheet" href="assets/vendors/select2/css/select2.min.css">

<script type="text/javascript" src="assets/vendors/select2/js/select2.min.js"></script>

【问题讨论】:

  • 为什么不把那个jquery插件引用插入到html中呢?
  • select2 是示例,我有很多插件,如果我在 html 中插入 jquery 插件引用,我的页面加载速度会降低。
  • 是 $.getScript("myurl/js/bootstrap-popover.js");也是一种方式。
  • 如果我在 html 中插入 jquery 插件引用,我的页面加载速度会降低 我的意思是将插件引用包含在 AJAX 返回的 html 响应中。虽然 CSS 不能这样包含,但 JS 可以。

标签: javascript jquery ajax dynamic jquery-plugins


【解决方案1】:

试试这个

//Declare a script with id
<script type="text/javascript" id="pluginJS"></script>
$(document).ready(function () {
    $("#pluginJS").attr("src", "pluginJS.js");

    $("#pluginJS").load(function () {
        $("#otherJS").attr("src", "other-plugin.js");
    });
})

Ajax 成功后调用

 $(document).on("click", "#page1", function () {
        $.ajax({
            type: 'POST',
            url: "/example-page1",
            success: function (result) {
                $('.ajax_content').html(result);

                //you can call JS Here
                $("#pluginJS").attr("src", "pluginJS.js");
                $("#pluginJS").load(function () {
                         //After Load PluginJS you can use jQuery
                         Initialize();
                });
            },
        })
})

【讨论】:

  • 我有很多插件,想降低页面加载速度。我想在每个页面加载 js,例如 select2 插件
  • 是的,你可以加载任何我提到的源代码。在页面加载后应用 src 到脚本,你可以调用哪个插件来加载什么条件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
  • 1970-01-01
相关资源
最近更新 更多