Obinwanne Hill Obinwanne Hill - 6 months ago 20
jQuery Question

Firefox not executing JavaScript files that were loaded dynamically

I'm trying to load two scripts that were functionally deferred on account of their

type
attributes being non-standard i.e.
text/javascript/defer
. Doing this causes the parser to ignore them so I want to reload them using JavaScript.

My HTML is as below:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>No Title</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">

<script type="text/javascript/defer" src="assets/js/test3.js"></script>
<script type="text/javascript/defer" src="assets/js/test4.js"></script>

<script type="text/javascript" src="assets/js/jquery.js"></script>
<script>

$(document).ready(function(){

var defer_js_collection_obj = $("[type='text/javascript/defer']"),
el_head_rq_obj = $('head'),
el_head_obj = el_head_rq_obj[0]
;

if(defer_js_collection_obj.length > 0)
{
//Reload JavaScript
defer_js_collection_obj.each(function() {

var file_src_outer_html_str = this.outerHTML;
var file_src_res_arr = file_src_outer_html_str.match("src *\= *[\"\']{1}(.*?)[\"\']{1}");
var file_src_str = file_src_res_arr[1];

var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file_src_str);
document.getElementsByTagName("head")[0].appendChild(fileref);
});

//Unload JavaScript with defer tag
for(var j = defer_js_collection_obj.length-1; j >= 0; j--)
{
defer_js_collection_obj[j].parentNode.removeChild(defer_js_collection_obj[j]);
}
}

});

</script>
</head>
<body>
<div>Load Deferred JavaScript</div>
</body>
</html>


jquery.js
is version 1.11.2.
test3.js
and
test4.js
reference the javascript files I want to load, and they contain
console.log('test3.js is loaded');
and
console.log('test4.js is loaded');
respectively.

The issue I'm having is that this script works virtually everywhere else except on Firefox. I'm on a Mac OS X 10.10.5 using Firefox 46.0.1, and I don't see the
console.log
message when I load the script.

How can I fix this?

Answer

It might be a mime type issue. Do you happen to see any message in the console stating "not well-formed"? In any case, this seemed to work for me and I agree that your code did not work in FF when I first tried it.

    $(document).ready(function(){
        console.log("main");

        var $body = $($("body")[0]);
        var $scripts = $("[type='text/javascript/defer']");

        $scripts.each(function(){
            var scriptTag = document.createElement("script");
            scriptTag.setAttribute("type", "text/javascript");
            scriptTag.setAttribute("src", $(this).attr("src"));
            $body.append(scriptTag);
        });
    });