PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

[FIXED] how to load external javascript inside partial view dynamically?

 May 18, 2022     html, javascript, partial     No comments   

Issue

I'm using jquery's .html() function to inject a html file into a partial div of the main page of my application. In the injected partial html page, there is a javascript reference such as script(src='../../javascripts/partialFunctions.js'). The jquery function and the main page are like:

$('.partialDiv').html(htmlResult);

<div>main page</div>
<div class='partialDiv'></div>
<input type='button'>button</input>

When the user click a specific button on the main application page, the jquery function will got called and the html file will got injected to the main page.

The problem is every time a new htm file got injected, the browser will load the script file. So there will be many duplicated javascript functions after the user clicked the button several times.

How can I do this dynamically and avoid the duplication of javascript functions?

Thanks in advance!


Solution

You can remove the script tags and references from the htmlResult page. Then use $.getScript('myscript.js') to import the necessary JavaScript files. More info on getScript() here

So to load in the script and make sure it only loads in once:

var window.foo = false; //Outside the document.ready

$('.partialDiv').html(htmlResult);
if(window.foo == false){
    $.getScript("js/myScript.js", function(data, textStatus, jqxhr){
        console.log('Script loaded');
        window.foo = true;
    });
}


Answered By - Navigatron
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing