Currently I have a widget which you insert somewhere on you page with the following
<script src='http://domain.com/public/jsonp/widget.js' data-id='LFKkv' data-width='240'></script>
I would like to load this dynamically after the page has loaded, I have tried jQuery $.getScript
like below, which fails miserably:
$.getScript("http://domain.com/public/jsonp/widget.js' data-id='LFKkv' data-width='240'", function(data){ ... })
Because of the spaces on the URL between the data attributes I assume.
I could use ajax but I don't know how to pass data attributes via the jQuery ajax call? How do I dynamically load the above widget with data attributes intact?
EDIT: Including the relevant parts of my widget script so you can see how my widget grabs the data attributes:
<script>
var scriptName = "widget.js";
TGW = window.jQuery.noConflict(true);
var allScripts = document.getElementsByTagName('script');
var targetScripts = [];
for (var i in allScripts) {
var name = allScripts[i].src
if(name && name.indexOf(scriptName) > 0)
targetScripts.push(allScripts[i]);
}
scriptTag = targetScripts[targetScripts.length - 1];
// Getting the data attributes here
jScript = TGW(scriptTag);
id = jScript.data("id");
widget_width = jScript.data("width");
</script>
Try passing options
object to an "init" function which loads widget,js
, set options
on widget at success
callback of "init" function
TGW = window.jQuery.noConflict(true);
function initWidget (options) {
return TGW.ajax({
url: url,
dataType: "script"
})
.then(function(script) {
// if `TGW.widgetName()` requires several seconds to load,
// try adding adding `setTimeout` or `.delay` to wait
// until `TGW.widgetName` defined before returning `TGW.widgetName`
return options && TGW.widgetName
? TGW.widgetName(options)
: TGW.widgetName(/* defaults?, are `id`, `width` required? */);
});
};
initWidget({"id":"LFKkv", "width":"240"})
.then(function(widget) {
console.log(widget)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With