prem prem - 1 month ago 12
jQuery Question

Dynamically adding a script/function block in jquery

EDITED:

Just wondering if is it possible to add a function (or static script) block or a variable to body of html.

Something like this,

$('body').add(function(){/../})


or

$('body').append('<script></script>')


or

$('body').fn.myFunc = function(){}


Is it correct to use .extend instead?

One example is if I use ExternalInterface, my callbacks have to be statically defined in body/html/js but not in $().ready function unless I have a var defined globally and refer it in $().ready function.

I overlooked this requirement, and thats where I wanted to add dynamic callback functions.

Answer
  • To create a script tag in your markup

    $('<script/>', {
        type:    'text/javascript',
        src:     'http://...'
    }).appendTo(document.body);
    
  • To extend jQuery use

    $.fn.yourmethodname = function(){
    });
    
Comments