StevieB
StevieB

Reputation: 6541

Changing Javascript method to Jquery

So I have the following Jquery calling a Javascript method

$j("a.Pinterest").attr("href", "javascript:void(addScript());");

And this is the Javascript Method

   function addScript() {
    var e = document.createElement('script');
    e.setAttribute('type', 'text/javascript');
    e.setAttribute('charset', 'UTF-8');
    e.setAttribute('src', 'http://assets.pinterest.com/js/pinmarklet.js?r=' + Math.random() * 99999999);
    return document.body.appendChild(e);
}

I was wondering if there was a way to have it all in Jquery ?

Upvotes: 0

Views: 312

Answers (4)

gen_Eric
gen_Eric

Reputation: 227310

$j("a.Pinterest").attr("href", "javascript:void(addScript());");

Please don't do this. I suggest using a click handler.

$j("a.Pinterest").click(addScript);

And then in your addScript you can use getScript to load the script.

function addScript(e) {
    e.preventDefault();
    $j.getScript('http://assets.pinterest.com/js/pinmarklet.js');
}

Upvotes: 1

mccow002
mccow002

Reputation: 6914

You can create elements in jQuery using the $ selector.

$('<script></script>')

jQuery is also chainable, so you can have this:

$('<script></script>')
    .attr({
        'type' : 'text/javascript',
        'charset', 'UTF-8',
        'src' : 'http://assets.pinterest.com/js/pinmarklet.js?r=' + Math.random() * 99999999)
     })
     .appendTo(whatever)

If you're doing conditional script loading, you might want to take a look at the yepnope library.

I would question why you're dynamically added a script to the page on a button click. Seems like you would want the script ready and waiting for the user to click. If you're worried about load time, but the script tag at the bottom of the page to defer the loading.

Upvotes: 0

Engineer
Engineer

Reputation: 48813

function addScript() {
      return $('<script/>',{
                          'type':'text/javascript',
                          'charset':'UTF-8',
                          'src':'http://assets.pinterest.com/js/pinmarklet.js?r=' + Math.random() * 99999999 
              }).appendTo("body")[0];
}

Upvotes: 0

Rick
Rick

Reputation: 1573

http://api.jquery.com/jQuery.getScript/

$.getScript("http://assets.pinterest.com/js/pinmarklet.js")
    .done(function(script, textStatus) {
     console.log( textStatus );
 })

edit: I didn't try this, I just took your address and threw it in the getScript demo.

Upvotes: 1

Related Questions