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/

5
  • 6
    So basically you want to write JS using JS. Why would you do this? You could just define a function and call it when needed. Commented Jun 2, 2015 at 10:24
  • < and > should be used Commented Jun 2, 2015 at 10:25
  • stackoverflow.com/questions/3857874/… Commented Jun 2, 2015 at 10:25
  • 1
    @HoschNok I'm building a chrome extension and I need to inject a script dynamically. Commented Jun 2, 2015 at 10:28
  • 1
    @GEspinha Chrome already has functions for this - developer.chrome.com/extensions/tabs#method-executeScript Commented Jun 2, 2015 at 10:29

2 Answers 2

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,
}))
Sign up to request clarification or add additional context in comments.

4 Comments

What if I have a larger script to add to the head?
you need to write every thing in text(). or you can directly call a function
May i know the reason why you want to code like this . when you can use any function or any logic base on events ??
I need this code to run a couple of scripts dynamically through a chrome extension, thanks :)
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?

2 Comments

The script in question doesn't have an src, it's just an inline script
Yes, I its just an inline script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.