Dimentica Dimentica - 1 month ago 5x
jQuery Question

Append javascript function to div

I need to add the following code to the footer of my page, but I have to do it using javascript code.

Code I need to add:

<script type="text/javascript">
(function (d, w, c) {
(w[c] = w[c] || []).push(function() {
try {
w.yaCounter39519115 = new Ya.Metrika({
} catch(e) { }

var n = d.getElementsByTagName("script")[0],
s = d.createElement("script"),
f = function () { n.parentNode.insertBefore(s, n); };
s.type = "text/javascript";
s.async = true;
s.src = "https://mc.yandex.ru/metrika/watch.js";

if (w.opera == "[object Opera]") {
d.addEventListener("DOMContentLoaded", f, false);
} else { f(); }
})(document, window, "yandex_metrika_callbacks");

What I try to add it:

$('#footer').append('<script type="text/javascript">' + (function (d, w,.... + '</script>');

However, this does not work for me.


Place your javascript in a separate .js file and then you need to use the document.createElement method to add/append your script to your footer block.

Try the below snippet.

var scriptSource = document.createElement('script');
var scriptURL = 'your_script_file_url_goes_here';
scriptSource.type = 'text/javascript';
scriptSource.src = scriptURL ;

Hope this helps!.