1

I'm linking a javascript file on my page like this:

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

I have some HTML elements loaded normally and at the same time I'm loading HTML content from another page like this with the same elements:

$( "#loaded_data-1" ).load( "Curriculum2.htm .half" , function( response, status, xhr ) {
        // but this content won't access example.js so I need to call it like this below.
$.getScript( "example.js");         
});

but this loaded content won't access example.js so I need to call through $.getScript( "example.js");.

But this causes problems for the original normally loaded elements because for them it is loaded twice. How do I load example.js once and apply to the all items on my site loaded the regular way and loaded with ajax?

Katerpiler
  • 119
  • 8

2 Answers2

2

Maybe it's a duplicate problem.

You can also use $.loadScript as follows:

$.loadScript('url_to_someScript.js', function(){
    //Do after someScript has loaded
}
OliK
  • 29
  • 4
  • It is not a duplicate. I already saw that question. From the script you can see I'm not loading the entire HTML page only certain parts. – Katerpiler Nov 22 '17 at 15:49
1

Remove your script tag:

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

Just add the script -- using your $.getScript() method -- once all of your HTML elements have been loaded. That way, the JavaScript won't be applied until all of your HTML elements are present and accounted for.

freginold
  • 3,946
  • 3
  • 13
  • 28
  • sorry that's not an option. I can't remove that because the first normally loaded elements won't work until the rest is loaded. – Katerpiler Nov 22 '17 at 15:46
  • Ah, okay. Is `example.js` your file? If so, maybe you could break it up into two scripts -- one to call right away, and another with code for the dynamic HTML elements added later. – freginold Nov 22 '17 at 16:34