How to dynamically insert a <script> tag through jQuery on a page from another page dynamically

I made a toolbar for my e-commerce site where there is an option for the selected page after selecting a specific page, if I click the save button, I want to dynamically run these codes on the selected page, with which I can use the scriptAnalytics.js file only for pages that I want.

var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src","scriptAnalytics.js")
document.getElementsByTagName("head")[0].appendChild(fileref)
+4
source share
2 answers

You can use the jQuery Ajax function to load and run the script:

$.ajax({
    url: url,
    dataType: "script",
    success: successFunction()
 });

or try using the abbreviated jQuery.getScript () method

+3
source

js jQuery.getScript() .

+2

Source: https://habr.com/ru/post/1502580/


All Articles