Skip to content Skip to sidebar Skip to footer

Load External Html File To Div And Use Its Js Functions

I have some div:
Now I want to load into this div an external html file and use its js functions. I know I can load it using jQuery.Load() and

Solution 1:

Pass parameter to view that you are loading that will indicate container of the loaded view:

jQuery.Load(url, { containerId: 'dialog' })

Solution 2:

I remember I had the problem back when jQuery1.4 was issued. In that version, .load() suddendly began stripping out the js when a target container was specified.

What I did at that time :

  1. separate html and js in different files (let's say myhtml.html and myjs.js ), or views
  2. have my js file act as a js module, with a public entry point function (say initContent) taking a jQuery element as a parameter
  3. have an invisible link in myhtml.html, namely <a href="myjs.js#initContent" class="dynamicJs" style="display:none;"></a>
  4. after loading myhtml.html into my target div, search for $('a.dynamicJs') in my target div to extract js url, and entry point function from the href
  5. if the js had not previously been loaded, dynamically load the js into the page trhough an ajax call
  6. dynamically call the entry point function with the target div as parameter

This also worked with css. It required some time to tweak it on all navigators (limited number of css sections on IE, different way to dynamically call a function), and I ended with much more code I expected in the first place. It also required a lot of refactoring of my html/js modules (but I must confess I ended having a code that was really cleaner)

I'm sure there are frameworks that handle this kind of situation way better by now. But this is what I came up with at that time.

Hope this will help


Post a Comment for "Load External Html File To Div And Use Its Js Functions"