简体   繁体   中英

How to include dynamic Javascript file in the DOM without repeating same file

I want to load <div> content dynamically by using AJAX in a specific div. After the AJAX call I want to load a JS file in the footer. I loaded content by clicking menu without page loading by using URL hash. My problem is when I click the same link multiple times, the JS file is loading multiple times because the JS file is appended. That's why every event occurs multiple times. I want to load the JS file before checking if the file is already loaded into the DOM. If the file is not loaded in the DOM, I will append a JS file in the DOM.

As the answer suggested by this URL , here is my code:

var Utils = {
  loadjs: function(url){
    var footer = document.getElementsByTagName('body')[0];
    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.src = url;
    footer.appendChild(script);
  },
}
Utils.loadjs(url);

You can read the script tags to search for a particular script is there or not. Something like below:

 var Utils = { loadjs: function(url) { var me = document.querySelectorAll('script[src="' + url + '"]'); if (me && me.length >= 1) { return null; } var footer = document.getElementsByTagName('body')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; footer.appendChild(script); }, } Utils.loadjs(url);

You can use dynamic import() syntax to load modules, even from regular scripts.

This has the benefit of loading those scripts as modules, which are always in strict mode and have module scope.

Read more about dynamic import

So, instead of Utils.loadjs(url) , just import(url)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM