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="" 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 = "";
    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

Here's where the error occurs (from

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


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.


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.

Need Your Help

Asynchronous requests from App Engine to Cloud Storage

google-app-engine google-cloud-storage google-cloud-platform

In my App Engine app I'm using Python Client for Google App Engine to read data from Cloud Storage.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.