1

I am trying to append a script tag with a script on the head of a page, but I am appending the code and it doesnt work. Probably because the page is already running.

How can I have something like this work?

$(document).ready(function () {
    $('a').on('click', function () {
        $('head').append('&ltscript&gtconsole.log("running")&lt/script&gt');
    });
});

http://jsfiddle.net/jtjmy5gy/6/

gespinha
  • 7,968
  • 16
  • 57
  • 91

2 Answers2

1

Try

DEMO

$(document).ready(function () {
  $('a').on('click', function () {
     $('<script>').text('console.log("running")').appendTo('head');
  });
});

EDIT

call Function using above Example : DEMO

$(document).ready(function () {
   $('a').on('click', function () {
     $('<script>').text('test()').appendTo('head');
   });
});

function test(){
  console.log("running")
}

Edit . you can also append script tag like below : DEMO

$("head").append($("<script />", {
   text: 'test()',
}))

$("head").append($("<script />", {
   html: 'test()',
}))

$("head").append($("<script />", {
   src: url,
}))
Nishit Maheta
  • 6,021
  • 3
  • 17
  • 32
0

You can put the script into a separate file, then use $.getScript to load and run it.

$.getScript("test.js", function(){
    alert("Running test.js");
});

Source: Rocket Hazmat

How to dynamically insert a <script> tag via jQuery after page load?

Community
  • 1
  • 1
George
  • 6,630
  • 2
  • 29
  • 36