A tip when running javascript dynamically

约定不等于承诺〃 2022-08-25 02:20 119阅读 0赞

firefox works differently from ie when change src of a existing script , in ie this action cause the javascript engine to reload that script, and execute it ,while in firefox, nothing will happen

you can have your own test by following code

  1. <
  2. script id
  3. =
  4. "
  5. s1
  6. "
  7. type
  8. =
  9. "
  10. text/javascript
  11. "
  12. >
  13. </
  14. script
  15. >
  16. <
  17. script language
  18. =
  19. "
  20. javascript
  21. "
  22. type
  23. =
  24. "
  25. text/javascript
  26. "
  27. >
  28. document
  29. .
  30. getElementById(
  31. "
  32. s1
  33. "
  34. )
  35. .
  36. src
  37. =
  38. "
  39. 1.js
  40. "
  41. ;
  42. </
  43. script
  44. >
  45. in 1.js we simply alert some message
  46. alert("executed");

So if you want the browser to execute some js dynamically , you need to reload the script element. Add a script element into DOM will cause the execution of the script in both browser ,following code shows how to reload a script element

  1. if
  2. (
  3. this
  4. .element)
  5. this
  6. .element.parentNode.removeChild(
  7. this
  8. .element);
  9. this
  10. .element
  11. =
  12. document.createElement(
  13. "
  14. SCRIPT
  15. "
  16. );
  17. this
  18. .element.type
  19. =
  20. "
  21. text/javascript
  22. "
  23. ;
  24. this
  25. .element.id
  26. =
  27. "
  28. MzJsonElement
  29. "
  30. ;
  31. this
  32. .element.src
  33. =
  34. url;
  35. document.getElementsByTagName(
  36. "
  37. HEAD
  38. "
  39. )[
  40. 0
  41. ].appendChild(
  42. this
  43. .element);

this might be helpful when we need our browser to run some json callback script

发表评论

表情:
评论列表 (有 0 条评论,119人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Javascript Tips & Tricks

    前端开发规范系列文章之Javascript Tips and Tricks,本意是写成常用代码收集、常用技巧整理的文章,感觉“常用代码大全”太土、“实用代码整理”有失偏颇,“提