superphonic
superphonic

Reputation: 8074

Dynamically loading JavaScript widget with data attributes

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>

Upvotes: 8

Views: 4483

Answers (5)

guest271314
guest271314

Reputation: 1

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)
});

Upvotes: 6

AmmarCSE
AmmarCSE

Reputation: 30597

Use jQuery load() like

$(window).load(function() {
    $('<script/>').attr({
        'src': 'http://domain.com/public/jsonp/widget.js',
        'data-id': 'LFKkv',
        'data-width': '240'
    }).appendTo('body')
});

Upvotes: 3

Abhishek sharma
Abhishek sharma

Reputation: 71

function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref) }   loadjscssfile("myscript.js", "js") //dynamically load and add this .js file loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

Upvotes: 2

Muhammad Umer
Muhammad Umer

Reputation: 18117

ok you should try this instead:

$.getScript("http://domain.com/public/jsonp/widget.js?data-id=LFKkv&data-width=240", function(data){ ... })

This is how you pass parameters in a url. You put ? and then start putting data=value&data2=value2 And it has to be properly html encoded.

Upvotes: 1

Grinde
Grinde

Reputation: 326

Can you wrap your widget in a function, and use an event listener?

window.addEventListener('load', function() {

    var allScripts = document.getElementsByTagName('script');
    var targetScripts = [];

    for (var i = 0; i < allScripts.length; i++) {
        var name = allScripts[i].src;
        if (name && name.indexOf(scriptName) > 0)
            targetScripts.push(allScripts[i]);
    }

    var scriptTag = targetScripts[targetScripts.length - 1];

    console.log( scriptTag.dataset.width );

});

Upvotes: 0

Related Questions