mayzul mayzul - 6 months ago 14
jQuery Question

loading external script ssource during on-click only


The code below always load script src when page load.


.

I have a website that clicks is on the right side(as menu item) then it loads page on the right side(content), but 1 page only.

.

How to load external script src during at onclick only?

<html>

<head>
<script src="https://xdomain.com/xout.js"></script>
</head>


<body>
<a href="#xrefer"> <img id="idxclick" src="images/ximage.jpg" /></a>

<script>
var handler = xout.xsetup({
key: 'sd_FlP9fKY7TvINq4bWachJQ35P',
image: '/images/xout.png',
locale: 'auto',
token: function(token) {
//
//
}
});

$('#idxclick').on('click', function(e) {
handler.open({
name: 'Hardware',
description: 'Software',
amount: '50.00'
});
e.preventDefault();
});

$(window).on('popstate', function() {
handler.close();
});
</script>

</body>
</html>


I did what your code > here > but same thing happen >

<html>

<head>
<!-- script src="https://xdomain.com/xout.js"></script> REMOVED -->
</head>


<body>
<a href="#xrefer"> <img id="idxclick" src="images/ximage.jpg" /></a>

<script>
$.getScript('https://xdomain.com/xout.js', function () {
// do some stuff after script is loaded

var handler = xout.xsetup({
key: 'sd_FlP9fKY7TvINq4bWachJQ35P',
image: '/images/xout.png',
locale: 'auto',
token: function(token) {
//
//
}
});

$('#idxclick').on('click', function(e) {
handler.open({
name: 'Hardware',
description: 'Software',
amount: '50.00'
});
e.preventDefault();
});

$(window).on('popstate', function() {
handler.close();
});

});
</script>

</body>
</html>

Answer

You can dynamically load a script with $.getScript() inside of your click event handler.

$('#idxclick').on('click', function(e) {
    $.getScript('https://xdomain.com/xout.js', function () {
        var handler = xout.xsetup({
                key: 'sd_FlP9fKY7TvINq4bWachJQ35P',
                image: '/images/xout.png',
                locale: 'auto',
                token: function(token) {
                    //
                    //
                };
        handler.open({
            name: 'Hardware',
            description: 'Software',
            amount: '50.00'
        });
    });
    e.preventDefault();
});
Comments