Crashalot
Crashalot

Reputation: 34523

Cannot read DOM attribute from script loaded dynamically

Including a script statically in the HTML like the one below works:

<script type="text/javascript" src="http://meerkatapp.co/widgets/embed.js" data-mute="false" data-social="false" data-cover="default" data-type="square" data-username="jessicadelfino"></script>

However, invoking the script dynamically doesn't work.

JavaScript code:

    // Create script object
    var script = document.createElement("script");

    // Configure script with Meerkat data
    script.type = "text/javascript";
    script.src = "http://meerkatapp.co/widgets/embed.js";
    script.setAttribute("data-mute", "false");
    script.setAttribute("data-social", "false");
    script.setAttribute("data-cover", "default");
    script.setAttribute("data-type", "square");
    script.setAttribute("data-username", "jessicadelfino");

    // Append script object
    $("body").append(script);

Here's where the error occurs (from http://meerkatapp.co/widgets/embed.js):

window.currentScript = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  return scripts[scripts.length - 1];
})();

main(window.currentScript)

function main(currentScript) {
      ...
      var btnContainerElm = currentScript
      var mkBtnUsername = btnContainerElm.getAttribute("data-username")
      ...
      mkBtnUsername = mkBtnUsername.replace("@", '')

This code generates the error: Uncaught TypeError: Cannot read property 'replace' of null on the line mkBtnUsername = mkBtnUsername.replace("@", '').

Clearly mkBtnUsername is not set even though the data-username attribute is set in the script.

Upvotes: 0

Views: 370

Answers (1)

user2844991
user2844991

Reputation:

My guess is document.currentScript is probably null (it can happen if that property is checked inside of an event handler, say $(document).ready), and your fallback function is choosing the wrong script (scripts[scripts.length - 1]). Try to log window.currentScript.

Upvotes: 1

Related Questions