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 ?
-
1Have a look at the jQuery documentation: api.jquery.com/jQuery.getScriptFelix Kling– Felix Kling2012年04月13日 15:47:23 +00:00Commented Apr 13, 2012 at 15:47
-
hmm, writing some code now, pls hold on abitA Person– A Person2012年04月13日 15:47:55 +00:00Commented Apr 13, 2012 at 15:47
-
Duplicates: stackoverflow.com/questions/4881164/…, stackoverflow.com/questions/9441142/…, stackoverflow.com/questions/5624366/…, stackoverflow.com/questions/4361033/jquery-load-script-on-clickFelix Kling– Felix Kling2012年04月13日 15:48:23 +00:00Commented Apr 13, 2012 at 15:48
-
1Instead of injecting inline JavaScript with jQuery, use a jQuery click handler.Sparky– Sparky2012年04月13日 15:48:43 +00:00Commented Apr 13, 2012 at 15:48
4 Answers 4
$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');
}
4 Comments
href attribute. Try $j("a.Pinterest").attr("href", "#");, or add href="#" to the link in the HTML.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.
Comments
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];
}
Comments
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.