5
$('#selector').click(function() {
    // here I would like to load a javascript file
    // let's say /js/script-on-click-event.js
});

Is that somehow possible? I'm not sure but I remember reading about a function that does this in JQuery documentation but I cannot find it here, maybe it's been deprecated or I saw it elsewhere?

Basically what I want is to load a script on a click event.

vsync
  • 118,978
  • 58
  • 307
  • 400
Richard Knop
  • 81,041
  • 149
  • 392
  • 552

3 Answers3

10

You can do the same using only javascript:

var script = document.createElement('script');
script.src = 'http://somesite.com/somescript.js';
script.type = 'text/javascript';
document.body.parentNode.appendChild(script);
Cleiton
  • 17,663
  • 13
  • 46
  • 59
9

Something like jQuery.getScript

$("#selector").click(function(){
  $.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js");
});
vsync
  • 118,978
  • 58
  • 307
  • 400
  • hi @vsync, will it appends into **DOM** multiple times? please tell –  Apr 26 '18 at 04:17
  • 1
    @EaB - good question. see [this thread](https://stackoverflow.com/a/5108063/104380) for more information. `getScript` doesn't append anything to the DOM, but it will download the script and execute it every time `getScript` for the *same* URL is called. You should place your own safety mechanism to prevent such a thing. – vsync Apr 26 '18 at 10:09
1

A library that makes this work is LAB JS

andres descalzo
  • 14,887
  • 13
  • 64
  • 115